在进程运行时读取其输出
我需要启动一个进程,并在这个进程运行的时候读取它的输出。我希望能够打印这个输出(这一步是可选的),并在进程结束后返回这个输出。以下是我目前的代码(是从StackOverflow上其他答案合并而来的):
def call(command, print_output):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out = ""
while True:
line = process.stdout.readline().rstrip().decode("utf-8")
if line == '':
break
if print_output:
print(line)
out += line + "\n"
process.wait()
return process.returncode, out
这段代码在Windows上运行得很好(我在Windows 7和Python 3.3上测试过),但是在Linux上(Ubuntu 12.04,Python 3.2)就不行了。在Linux上,脚本在以下这一行卡住了:
line = process.stdout.readline().rstrip().decode("utf-8")
当进程结束时。
这段代码哪里出问题了?我也试着用process.poll()来检查进程是否结束,但在Linux上这个方法总是返回None。
1 个回答
0
文档上说
Warning Use communicate() rather than
.stdin.write, .stdout.read or .stderr.read to
avoid deadlocks due to any of the other OS pipe buffers filling
up and blocking the child process.
我知道我之前在Windows上遇到过问题。
我猜这个命令可能是在某种情况下以无缓冲模式运行的。
文档里有关于如何使用subprocess的说明,你提到的听起来像是shell-backquote,但你使用的subprocess
方式不太一样。