0

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:

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?

P.S. Python 3.4.1 (IPython via Anaconda), Mac OS X

Korem
  • 11,383
  • 7
  • 55
  • 72
night_bat
  • 3,212
  • 5
  • 16
  • 19

2 Answers2

3

Some programs write to stdout and also 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:

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
johntellsall
  • 14,394
  • 4
  • 46
  • 40
  • Works just fine. Thank a lot! By the way, it appears `subprocess.Popen(...)` also could handle this. What method is better? – night_bat Jul 17 '14 at 18:30
  • I like the `check_xx` functions because they raise exceptions if the program exits with an error. They're obvious, and I like obvious :) – johntellsall Jul 17 '14 at 19:13
  • @user3058525: A program may also [print to a terminal directly](http://stackoverflow.com/a/20981435/4279). You might need `screen` utility to capture such output. – jfs Sep 21 '14 at 14:34
  • 1
    nitpick: use `universal_newlines=True` on Python 3 to enable the text mode. And `print s` -> `print(s)`. – jfs Sep 21 '14 at 14:35
2

If your program prints to STDOUT, you are using subprocess.check_output correctly. 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