I want to get the output from some shell commands like ls
or df
in a python script. I see that commands.getoutput('ls')
is deprecated but subprocess.call('ls')
will only get me the return code.
I'll hope there is some simple solution.
Use subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
Note that communicate blocks until the process terminates. You could use process.stdout.readline() if you need the output before it terminates. For more information see the documentation.