I can execute a terminal command using os.system() but I want to capture the output of this command. How can I do this?
4 Answers
>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print(output)
arg1 arg2
There is a bug in using of the subprocess.PIPE. For the huge output use this:
import subprocess
import tempfile
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
proc.wait()
tempf.seek(0)
print(tempf.read())
1 Comment
RAZ_Muh_Taz
you are my savior!!! i have been looking for something like this for days!!! thank you!
The recommended way in Python 3.5 and above is to use subprocess.run():
from subprocess import run
output = run("pwd", capture_output=True).stdout
11 Comments
Cherona
PIPE is not defined
Sven Marnach
@Cherona It's deifned in the
subprocess module, so you need to import it.Sven Marnach
I also updated the answer with the most recent API to do this.
Sven Marnach
@HelenCraigman I see. On Unix, you can still read from the "controlling terminal" by opening
/dev/tty for reading and writing. I'm not sure that pattern is a good idea, though.fourk
FileNotFoundError: [WinError 2] The system cannot find the file specified
|
You can use Popen in subprocess as they suggest.
with os, which is not recomment, it's like below:
import os
a = os.popen('pwd').readlines()
3 Comments
Sven Marnach
This does not work.
Popen objects have no readlines() method.gerry
Thanks for pointing it out, it only works for os.popen
Sven Marnach
os.popen is deprecated in favour of subprocess.Popen.The easiest way is to use the library commands
import commands
print commands.getstatusoutput('echo "test" | wc')
2 Comments
Brōtsyorfuzthrāx
Where do you get the commands module? It doesn't appear to be on pip for Python3.
aaroh
@Shule commands is an older module. It is replaced by the subprocess module. docs.python.org/2/library/…