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

2
  • How many lines printed from the process? Commented Jul 10, 2014 at 7:53
  • don't use a list argument with shell=True it is an error in most cases. Commented Sep 21, 2014 at 14:36

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

4 Comments

Works just fine. Thank a lot! By the way, it appears subprocess.Popen(...) also could handle this. What method is better?
I like the check_xx functions because they raise exceptions if the program exits with an error. They're obvious, and I like obvious :)
@user3058525: A program may also print to a terminal directly. You might need screen utility to capture such output.
nitpick: use universal_newlines=True on Python 3 to enable the text mode. And print s -> print(s).
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.