Python 读取子进程的标准

Python 读取子进程的标准,python,subprocess,Python,Subprocess,我在使用subprocess.Popen时遇到了一个问题。我解决了这个问题。将以下编辑添加到伪_utility.py时,即在subprocess.Popen中添加stderr=subprocess.PIPE: #fake_utility.py import time i = 0 while True: print hex(i)*512 i += 1 time.sleep(0.5) #python interpreter import subprocess proc = sub

我在使用subprocess.Popen时遇到了一个问题。我解决了这个问题。将以下编辑添加到伪_utility.py时,即在subprocess.Popen中添加stderr=subprocess.PIPE:

#fake_utility.py
import time
i = 0
while True:
   print hex(i)*512
   i += 1
   time.sleep(0.5)

#python interpreter
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for err in proc.stderr:
    print "err::", err

for line in proc.stdout:
   print "test:", line.rstrip()
程序没有响应。当我按下Ctrl-C键时,会得到以下结果:

Traceback (most recent call last):
File "run_fake_utility.py", line 6, in <module>
    err = proc.stderr.readline()
KeyboardInterrupt
回溯(最近一次呼叫最后一次):
文件“run\u fake\u utility.py”,第6行,在
err=proc.stderr.readline()
键盘中断
正在进程stderr.readline()中阻止它。如果我从proc.stderr中删除行读取,程序运行正常


可能的错误是什么?我使用的是Python2.6。

从STDERR读取时阻塞表示子进程没有向该文件句柄写入任何内容

你真的在期待什么吗?(即:如果从shell手动运行相同的命令,并将STDERR-
2>file.txt重定向到一个文件,该文件是否为非空?)

否则,可能会发生一些常见情况:

  • 您尚未在STDERR输出中收到换行符
  • 您尚未收到足够的数据来填充一些底层缓冲区

如果有错误,我只想打印出来。我从shell手动运行命令,将STDERR重定向到文件,它是空的。这意味着,如果STDERR输出中没有任何内容,那么程序将永远阻塞。如何避免这种情况?@like.one使用或在一定时间内终止线程。