简体   繁体   English

无法从子流程check_output检索输出

[英]Can't retrieve output from subprocess check_output

I'm wondering how to save the output of the program in a file. 我想知道如何将程序的输出保存到文件中。

In particular, I'm trying to save all output from vowpal_wabbit application to a file, when running it from the Python like that: 特别是,当我像这样从Python运行它时,我试图将vowpal_wabbit应用程序的所有输出保存到文件中:

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

However it printed out nothing, while the program itself executes well. 但是,在程序本身执行良好的同时,它什么也没打印出来。 It's strange because when run from the Terminal with the very same parameters it provides me some useful information. 这很奇怪,因为从终端以相同的参数运行时,它为我提供了一些有用的信息。

Can anyone suggest a solution? 谁能提出解决方案?

PS Python 3.4.1 (IPython via Anaconda), Mac OS X PS Python 3.4.1(通过Anaconda的IPython),Mac OS X

Some programs write to stdout and also stderr. 一些程序会写入stdout以及stderr。 To build on @Tichodroma's code, the following prints 'stdout' to stdout, 'stderr' to stderr, merges the two streams, and captures both outputs correctly: 为了建立在@Tichodroma的代码上,以下代码将“ stdout”打印到stdout,将“ stderr”打印到stderr,合并两个流,并正确捕获两个输出:

source 资源

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'

output 产量

DATA: stdout.stderr.
END

If your program prints to STDOUT , you are using subprocess.check_output correctly. 如果程序打印到STDOUT ,则说明您正确使用了subprocess.check_output A working example: 一个工作示例:

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

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM