Retrieving the output of subprocess.call() [duplicate] Retrieving the output of subprocess.call() [duplicate] python python

Retrieving the output of subprocess.call() [duplicate]


If you have Python version >= 2.7, you can use subprocess.check_output which basically does exactly what you want (it returns standard output as string).

Simple example (linux version, see note):

import subprocessprint subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])

Note that the ping command is using linux notation (-c for count). If you try this on Windows remember to change it to -n for same result.

As commented below you can find a more detailed explanation in this other answer.


Output from subprocess.call() should only be redirected to files.

You should use subprocess.Popen() instead. Then you can pass subprocess.PIPE for the stderr, stdout, and/or stdin parameters and read from the pipes by using the communicate() method:

from subprocess import Popen, PIPEp = Popen(['program', 'arg1'], stdin=PIPE, stdout=PIPE, stderr=PIPE)output, err = p.communicate(b"input data that is passed to subprocess' stdin")rc = p.returncode

The reasoning is that the file-like object used by subprocess.call() must have a real file descriptor, and thus implement the fileno() method. Just using any file-like object won't do the trick.

See here for more info.


For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess object, from which you can easily obtain the output as well as return code.

from subprocess import PIPE, runcommand = ['echo', 'hello']result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)print(result.returncode, result.stdout, result.stderr)


matomo