从子进程stdout / stderr读取并在生成时将其打印到屏幕是棘手的,因为它很容易陷入死锁。将子进程stdout / stderr重定向到sys.stdout / sys.stderr是否有任何不利之处,这似乎容易得多?代码示例:
import shlex
import subprocess
import time
def run(command):
p = subprocess.Popen(shlex.split(command), stdout=sys.stdout, stderr=sys.stderr)
while True:
return_code = p.poll()
if return_code is not None:
if return_code > 0:
raise Exception("Command %s failed" % command)
break
else:
time.sleep(1)