How can I get terminal output in python?
Question:
I can execute a terminal command using os.system()
but I want to capture the output of this command. How can I do this?
Answers:
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
>>> 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()
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()
The easiest way is to use the library commands
import commands
print commands.getstatusoutput('echo "test" | wc')
I can execute a terminal command using os.system()
but I want to capture the output of this command. How can I do this?
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
>>> 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()
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()
The easiest way is to use the library commands
import commands
print commands.getstatusoutput('echo "test" | wc')