python getoutput() equivalent in subprocess

PythonShellCommandSubprocess

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

For Python >= 2.7, use subprocess.check_output().

http://docs.python.org/2/library/subprocess.html#subprocess.check_output

Solution 3 - Python

To catch errors with subprocess.check_output(), you can use CalledProcessError. If you want to use the output as string, decode it from the bytecode.

# \return String of the output, stripped from whitespace at right side; or None on failure.
def runls():
    import subprocess
    try:
        byteOutput = subprocess.check_output(['ls', '-a'], timeout=2)
        return byteOutput.decode('UTF-8').rstrip()
    except subprocess.CalledProcessError as e:
        print("Error in ls -a:\n", e.output)
        return None

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRafael TView Question on Stackoverflow
Solution 1 - PythonMichael SmithView Answer on Stackoverflow
Solution 2 - PythonkniteView Answer on Stackoverflow
Solution 3 - PythonRoi DantonView Answer on Stackoverflow