python getoutput() equivalent in subprocess

Rafael T picture Rafael T · Jul 12, 2011 · Viewed 97.1k times · Source

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.

Answer

Michael Smith picture Michael Smith · Jul 12, 2011

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.