Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python getoutput() equivalent in subprocess [duplicate]

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.

like image 400
Rafael T Avatar asked Jul 11 '11 22:07

Rafael T


People also ask

How do I get stdout from subprocess run Python?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

How do I get the subprocess Popen output?

popen. To run a process and read all of its output, set the stdout value to PIPE and call communicate(). The above script will wait for the process to complete and then it will display the output.

How do you get stdout and stderr from subprocess run?

If you simply want to capture both STDOUT and STDERR independently, AND you are on Python >= 3.7, use capture_output=True .

How do I use Popen in Python?

Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.


3 Answers

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.

like image 117
Michael Smith Avatar answered Oct 17 '22 17:10

Michael Smith


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

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

like image 27
knite Avatar answered Oct 17 '22 18:10

knite


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
like image 10
Roi Danton Avatar answered Oct 17 '22 16:10

Roi Danton