Python: How to get stdout after running os.system?
Solution 1
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.
Solution 2
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()
Solution 3
import subprocess
string="echo Hello world"
result=subprocess.getoutput(string)
print("result::: ",result)
Solution 4
I had to use os.system, since subprocess was giving me a memory error for larger tasks. Reference for this problem here. So, in order to get the output of the os.system command I used this workaround:
import os
batcmd = 'dir'
result_code = os.system(batcmd + ' > output.txt')
if os.path.exists('output.txt'):
fp = open('output.txt', "r")
output = fp.read()
fp.close()
os.remove('output.txt')
print(output)
Solution 5
I would like to expand on the Windows solution. Using IDLE with Python 2.7.5, When I run this code from file Expts.py:
import subprocess
r = subprocess.check_output('cmd.exe dir',shell=False)
print r
...in the Python Shell, I ONLY get the output corresponding to "cmd.exe"; the "dir" part is ignored. HOWEVER, when I add a switch such as /K or /C ...
import subprocess
r = subprocess.check_output('cmd.exe /K dir',shell=False)
print r
...then in the Python Shell, I get all that I expect including the directory listing. Woohoo !
Now, if I try any of those same things in DOS Python command window, without the switch, or with the /K switch, it appears to make the window hang because it is running a subprocess cmd.exe and it awaiting further input - type 'exit' then hit [enter] to release. But with the /K switch it works perfectly and returns you to the python prompt. Allrightee then.
Went a step further...I thought this was cool...When I instead do this in Expts.py:
import subprocess
r = subprocess.call("cmd.exe dir",shell=False)
print r
...a new DOS window pops open and remains there displaying only the results of "cmd.exe" not of "dir". When I add the /C switch, the DOS window opens and closes very fast before I can see anything (as expected, because /C terminates when done). When I instead add the /K switch, the DOS window pops open and remain, AND I get all the output I expect including the directory listing.
If I try the same thing (subprocess.call instead of subprocess.check_output) from a DOS Python command window; all output is within the same window, there are no popup windows. Without the switch, again the "dir" part is ignored, AND the prompt changes from the python prompt to the DOS prompt (since a cmd.exe subprocess is running in python; again type 'exit' and you will revert to the python prompt). Adding the /K switch prints out the directory listing and changes the prompt from python to DOS since /K does not terminate the subprocess. Changing the switch to /C gives us all the output expected AND returns to the python prompt since the subprocess terminates in accordance with /C.
Sorry for the long-winded response, but I am frustrated on this board with the many terse 'answers' which at best don't work (seems because they are not tested - like Eduard F's response above mine which is missing the switch) or worse, are so terse that they don't help much at all (e.g., 'try subprocess instead of os.system' ... yeah, OK, now what ??). In contrast, I have provided solutions which I tested, and showed how there are subtle differences between them. Took a lot of time but... Hope this helps.
Eduard Florinescu
Coding my way out of boredom. “If the fool would persist in his folly he would become wise.” (William Blake)
Updated on October 21, 2020Comments
-
Eduard Florinescu over 3 years
I want to get the
stdout
in a variable after running theos.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 or1
under some linux for the above example).How can I get the
stdout
for the above command without using redirection in the executed command? -
Eduard Florinescu over 10 yearsIn Windows works only if the cmd.exe is ran
result = subprocess.check_output(["cmd.exe", batcmd])
-
Martijn Pieters over 10 years@EduardFlorinescu: Or use
shell=True
; this was mentioned in thesubprocess
documentation but I've made it explicit here. -
JohnnyLinTW over 7 yearsYour solution (subprocess.call("cmd.exe dir",shell=False) )is work under ubuntu 12.04 except shell=True. Thanks!
-
RjOllos over 6 yearsKeep in mind that it is deprecated since Python 2.6.
-
mbhargav294 over 4 yearsdeprecated == no further code changes/fixes will be made to the library
-
Randy over 4 yearsYou may want to add an explanation on why this answer is an improvement on the current high ranking answer. If it's a new api, or something was deprecated, it's important so others can differentiate the pros and cons.
-
Robert Lugg about 4 yearsThanks. Sadly still, some of us are using 2.6!
-
Charles Duffy about 4 years
os.system()
also usesfork()
/clone()
under the hood, so how is this any better? -
Charles Duffy about 4 years...and also liable to be removed in a future version.
-
Edhowler about 4 yearsAll I know is that one method worked and the other didn't. I'm using ubuntu and this command: out = os.system('ffmpeg -i ' + converted_filename + ' -ss ' + str(thumbnail_frame_time) + ' -vf scale=254:152 -vframes 1 -vcodec png -an -y ' + file_name + '.png')
-
Charles Duffy about 4 yearsThat's dangerously insecure. Use
shlex.quote()
(or its python 2.x equivalentpipes.quote()
) on all your filenames before substituting them into UNIX commands, or someone who drops a file in your upload folder named$(rm -rf ~)'$(rm -rf ~)'.mpg
can cause you to have a very bad day. -
Edhowler about 4 yearsYou are right, thanks.
-
Louis Yang about 4 yearsIs there a way to do this in Jupyter Notebook? Looks like it only return an empty string.
-
Martijn Pieters about 4 years@LouisYang: yes, this works in Jupyter notebooks too. But take into account that the current working directory of the Python subprocess may differ, you may want to set the
cwd
argument tosubprocess.check_output()
. -
root almost 4 yearsIt should be mentioned that this does use legacy carry overs from the commands module from Python 2, however it is not marked as deprecated in the API documentation found here: docs.python.org/3/library/subprocess.html#subprocess.getoutput This helped me a ton because I had a process that is rather old, and doesn't return 0 on successful invocations, meaning check_output couldn't be used, and call() wasn't working as intended. Upvoted!