【发布时间】:2012-11-02 09:37:18
【问题描述】:
我使用 subprocess.Popen 实现了一个 python 程序来执行从服务器到 Ubuntu 客户端的命令。子进程必须逐行读取所有输出。 我的程序在 Eclipse 环境下完美运行。所有输出都按我的预期打印。 但是当我在 Python 交互式 shell(在 Windows 和 Linux 中)下运行程序时, subprocess.Popen 没有读取所有命令输出。输出只显示很少,然后 Python 崩溃而没有任何错误。这是我的程序代码:
def execute(self, IP_Instance, command):
keypairs_directory = Config.keypairs_directory
cmd = 'ssh ubuntu@%s'%IP_Instance+' -i %s'%keypairs_directory+' %s'%command
cmd_run = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
for line in cmd_run.stdout:
print line
cmd_run.wait()
例如,当我发送命令时:
a.execute('xxx.xxx.xxx.xxx', 'ls -l')
我有输出
total 0
没关系。但是当我发送时:
a.execute('xxx.xxx.xxx.xxx', 'sudo apt-get update')
程序只运行到
Fetched 8,364 kB in 6s (1,205 kB/s)
Reading package lists...
然后 Python 回到
>>>
我曾尝试过communicate()[0]、poll(),但它们并没有带来效果。我对所有机器都使用 Python 2.7。我究竟做错了什么?
【问题讨论】:
-
如何返回交互式提示映射到“崩溃而没有任何错误”?如果你改为
return cmd_run.wait(),你会得到什么返回码?
标签: python shell ide subprocess popen