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?
If all you need is the
stdout
output, then take a look atsubprocess.check_output()
:Because you were using
os.system()
, you'd have to setshell=True
to get the same behaviour. You do want to heed the security concerns about passing untrusted arguments to your shell.If you need to capture
stderr
as well, simply addstderr=subprocess.STDOUT
to the call:to redirect the error output to the default output stream.
If you know that the output is text, add
text=True
to decode the returned bytes value with the platform default encoding; useencoding="..."
instead if that codec is not correct for the data you receive.