阅读python STDOUT实时

时间:2014-12-16 15:36:26

标签: python subprocess stdout

我的代码如下,基本上这个模块将运行所需的命令并逐行捕获其输出,但在我的情况下,当命令运行时,返回命令提示符只需要一秒多的时间,那就是子进程.stdout.read(1)挂起,如果我使用它运行一个正常的命令,它会按预期打印everthing。但在特定情况下,命令会将某些内容打印到STDOUT然后需要一些时间才能返回到提示符,它会挂起..请帮忙

新代码:

def run_command(shell_command):
'''run the required command and print the log'''
child = subprocess.Popen(shell_command, shell=True,stdout=subprocess.PIPE)
(stdoutdata, stderrdata) = child.communicate()
print stdoutdata

print "Exiting.."

错误:

  File "upgrade_cloud.py", line 62, in <module>
stop_cloud()
File "upgrade_cloud.py", line 49, in stop_cloud
run_command(shell_command)
 File "upgrade_cloud.py", line 33, in run_command
 (stdoutdata, stderrdata) = child.communicate()
 File "/usr/lib/python2.6/subprocess.py", line 693, in communicate
stdout = self.stdout.read()
KeyboardInterrupt

1 个答案:

答案 0 :(得分:3)

这是你的问题:

child.wait()

这一行导致Python等待子进程退出。如果子进程试图将大量数据打印到stdout,它将阻止等待Python读取所述数据。由于Python正在等待子进程并且子进程正在等待Python,因此会出现死锁。

我建议使用subprocess.check_output()代替subprocess.Popen。您也可以使用Popen.communicate()方法代替.wait()方法。

相关问题