我已阅读并尝试了8种不同的方法来解答有关此问题的几个问题。我用python打开了一个进程,并且想要读取它的输出,即使这个进程还没有结束。该过程通常不会持续至少1分钟或直到发送中断。无论我尝试什么,我都无法读取输出结果。我知道我通过工作的命令和参数,因为当我将其更改为subprocess.call(cmd,args)时,它会将所有内容打印到屏幕上。我也检查过程是用ps -ax运行的。下面是我想要一个例子(猫的/ dev /随机无关我的项目):无法从正在运行的进程读取标准输出
proc = subprocess.Popen(["cat", "/dev/random"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print("Process started.")
这是我已经试过至今未能:
for line in iter(p.stdout.readline, ''):
strLine = str(line).rstrip()
print(">>> " + strLine)
sys.stdout.flush()
而且
output, error = proc.communicate()
print output
而且
while proc.poll() is None:
print("Still waiting.")
print(proc.stdout.readline(1))
我尝试过的更多解决方案是这种变体,但没有运气。在不改变标准输出的情况下使用调用函数时,所有东西都可以正确输出到控制台。我究竟做错了什么?
我正在使用Python 2.6。
你的程序是否真的把它的输出发送到'stdout'而不是'stderr'?你检查了吗? –