Eduard Florinescu Eduard Florinescu - 5 months ago 16
Python Question

Python: How to get stdout after running os.system?

I want to get the

stdout
in a variable after running the
os.system
call.

Lets take this line as an example:

batcmd="dir"
result = os.system(batcmd)


result
will contain the error code (
stderr
0
under Windows or
1
under some linux for the above example).

How can I get the
stdout
for the above command without using redirection in the executed command?

Answer

If all you need is the stdout output, then take a look at subprocess.check_output() (added in Python 2.7):

import subprocess

batcmd="dir"
result = subprocess.check_output(batcmd, shell=True)

Because you were using os.system(), you'd have to set shell=True to get the same behaviour. You do want to heed the big red warning message about passing untrusted arguments to your shell.

If you need to capture stderr as well, simply add stderr=subprocess.STDOUT to the call:

result = subprocess.check_output([batcmd], stderr=subprocess.STDOUT)

to redirect the error output to the default output stream.