【问题标题】:Python Subprocess cannot read all outputs in shellPython Subprocess 无法读取 shell 中的所有输出
【发布时间】: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


【解决方案1】:

apt-get update 命令也以标准错误返回数据,因此您还需要捕获 stderr 数据:

subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

然后你必须同时使用Popen.stdoutPopen.stderr

【讨论】:

  • 感谢您的快速答复。我刚刚尝试过,但不幸的是结果还是一样。
  • stderr=subprocess.STDOUT 将重定向stderr
  • 我得到相同的输出。此外,我尝试了其他打印长输出的命令,并且程序也无法读取以打印所有内容。例如 sudo apt-get install -y mc。但是,在 Eclipse 中,所有操作都是一样的。
猜你喜欢
  • 2011-09-11
  • 1970-01-01
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 2017-05-11
  • 2015-09-09
  • 2022-01-05
  • 2022-01-01
相关资源
最近更新 更多