Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 483
Eduard Florinescu Avatar asked Sep 28 '22 16:09

Eduard Florinescu


People also ask

What does OS system return in Python?

The os. system() function executes a command, prints any output of the command to the console, and returns the exit code of the command.

How do I get output from subprocess?

To get a string as output, use “output. stdout. decode(“utf-8”)” method. You can also supply “text=True” as an extra argument to the subprocess.


2 Answers

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

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 security concerns 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.

If you know that the output is text, add text=True to decode the returned bytes value with the platform default encoding; use encoding="..." instead if that codec is not correct for the data you receive.

like image 164
Martijn Pieters Avatar answered Oct 28 '22 21:10

Martijn Pieters


These answers didn't work for me. I had to use the following:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
    return p.stdout.read()
like image 26
Patrick Avatar answered Oct 28 '22 22:10

Patrick