Python 运行 python 时 POpen Stdout 不返回

Python POpen Stdout not returning back when running python

阅读更新!!!

我在从子进程模块的 Python POpen 获取输出时遇到问题。

它在 'ls' 、 'node' 和 'python3 -m pip install requests'.

等命令上运行良好

但是当我 运行 一个简单的 python 文件时,例如 'python3 test.py' 包含:

print("Hello World!")

不输出。它也不适用于:

sys.stdout.write()

它是 运行 的代码,这可以通过将此代码放在 test.py

中来证明
f = open("text.txt","w")
f.write("Hello :P")
f.close()

并且写入文件就好了。

这是从主文件中提取的代码:

def executeCmd(cmd):
    filename = "cmdlog_{}.txt".format(cmd.replace(" ","-").replace(".","-").replace("/","-"))
    with io.open(filename, 'wb') as writer, io.open(filename, 'rb', 1) as reader:
        process = sb.Popen(cmd, stdout=writer,stderr=writer, cwd=oss.getcwd(),shell=True)
        while process.poll() is None:
            rd = reader.read()
            sys.stdout.write(rd.decode("UTF-8"))
            time.sleep(0.1)
        time.sleep(0.5)
        rd = reader.read().decode("UTF-8")
        sys.stdout.write(rd)
        time.sleep(0.5)
        oss.remove(filename)

作为额外信息,该函数被称为线程,来自另一个从套接字恢复数据的线程。因此下面的字典 'data' 和上面的发送函数。

threading.Thread(target=proccessListen,args=([data["cmd"],data["name"]]),daemon=True).start()

我束手无策,这个问题发生在多台 os 和机器上。 由于尚未找到修复程序,而且谷歌搜索了几个小时也找不到相关文章,我请求你的帮助

提前致谢,山姆。


更新: 在玩代码 1/2 小时并在线搜索以解决新问题后,我又遇到了障碍。

这是我的新代码:

import io
import sys
import os
import subprocess
import time

def executeCmd(cmd):
    process = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,cwd=os.getcwd(),shell=True)
    print("Started")
    while process.poll() is None:
      line = process.stdout.readline()
      sys.stdout.write(line)
      #process.stdout.flush()
      time.sleep(0.5)
    print("Ended")

executeCmd("python3 test.py")

并且在test.py

print("Hello")
count = 0
import time
while True:
  time.sleep(2)
  count = count + 1
  print("Output: {}".format(count))

问题是 process.stdout.readline() 阻塞了代码,这意味着它永远无法读取输出,但为什么。这是从 forum page 中获取并修改的。都没有用,都遇到了同样的问题,我已经搜索并解决了许多其他堆栈溢出问题,none 的解决方案 worked.I 也尝试了一些带有非阻塞标志的东西(我不是确定我在做什么)。它对其他人有用,但我得到了一个 OSERROR。虽然这看起来是一条很难走的路。

如有任何帮助,我们将不胜感激。

谢谢山姆

修复只花了更近的时间和一些阅读

多谢sarge。一个很棒的模块!

这是我的代码:

import sarge
import time
import sys

cmd = sarge.run("python3 test.py",async_=True,stdout=sarge.Capture(buffer_size=1))
print("Hello World")
while True:
  time.sleep(0.5)
  sys.stdout.write("." + str(cmd.stdout.read()))
  sys.stdout.flush()

可以修改代码以去掉 b''.

山姆


哦,谢谢你对这个问题投了反对票,你让我已经苦苦挣扎的代表回到了 1。谢谢。

process.poll() returns 子进程完成执行后 None 以外的内容。这说明 绝对没有 关于您是否阅读了子进程的所有输出!您需要在循环中不断调用 process.stdout.readline() 直到它 returns 一个空字符串 - 事实上,这是您在这种情况下唯一需要的循环,因为 process.poll() 没有给您任何信息你真的在用。