【问题标题】:Can't retrieve output from subprocess check_output无法从子进程 check_output 检索输出
【发布时间】:2014-07-10 07:44:21
【问题描述】:

我想知道如何将程序的输出保存在文件中。

特别是,当像这样从 Python 运行它时,我正在尝试将 vowpal_wabbit 应用程序的所有输出保存到一个文件中:

rez1 = subprocess.check_output([parameters], shell=True, universal_newlines=True)
print(rez1)

但是它什么也没打印出来,而程序本身执行得很好。这很奇怪,因为当从终端使用完全相同的参数运行时,它为我提供了一些有用的信息。

谁能提出解决方案?

附: Python 3.4.1(IPython 通过 Anaconda),Mac OS X

【问题讨论】:

  • 这个过程打印了多少行?
  • 不要在shell=True 中使用列表参数,这在大多数情况下是错误的。

标签: python python-3.x subprocess


【解决方案1】:

一些程序写入标准输出和标准错误。为了构建 @Tichodroma 的代码,以下将“stdout”打印到 stdout,将“stderr”打印到 stderr,合并两个流,并正确捕获两个输出:

来源

import subprocess

res = subprocess.check_output(
    "echo stdout; /bin/echo stderr 1>&2",
    shell=True,
    stderr=subprocess.STDOUT,
    )
print 'DATA:', res.replace('\n', '.')
print 'END'

输出

DATA: stdout.stderr.
END

【讨论】:

  • 工作得很好。非常感谢!顺便说一句,subprocess.Popen(...) 似乎也可以处理这个问题。什么方法比较好?
  • 我喜欢check_xx 函数,因为如果程序因错误退出,它们会引发异常。它们很明显,我喜欢明显:)
  • @user3058525:一个程序也可以print to a terminal directly。您可能需要screen 实用程序来捕获此类输出。
  • nitpick:在 Python 3 上使用 universal_newlines=True 启用文本模式。还有print s -> print(s)
【解决方案2】:

如果您的程序打印到STDOUT,则说明您正确使用了subprocess.check_output。一个工作示例:

res = subprocess.check_output("date", shell=True, universal_newlines=True)
print(res)

输出:

Thu Jul 10 09:49:31 CEST 2014\n

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 2016-07-10
    • 1970-01-01
    相关资源
    最近更新 更多