What Is the Return Value of Subprocess.Call()

Storing subprocess.call() return value in a variable

You can use subprocess.check_ouput as well. It was specifically meant for checking output as the name suggests.

count = subprocess.check_output("ls -l | awk '{print $1}' | wc -l", shell=True)

Get a return value using subprocess

Use subprocess.check_output() instead of subprocess.call().

Retrieving the output of subprocess.call()

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, PIPE

p = 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.

How can I get return values with subprocess?

If you open python non-interactively then it waits until it's read all of stdin before running the script, so your example won't work. If you write your commands and then close stdin before reading like in the following you can get the results out.

import subprocess

p = subprocess.Popen("python", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("print 1+3\n")
p.stdin.write("print 2+4\n")
p.stdin.close()
print p.stdout.read()

Alternatively, using "-i" to force python into interactive mode:

import subprocess

p = subprocess.Popen(["python", "-i"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write("1+3\n")
print p.stdout.readline()
p.stdin.write("2+4\n")
print p.stdout.readline()
p.stdin.write("4+6\n")
print p.stdout.readline()
p.stdin.close()

This produces:

Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> >>> 4

>>> 6

>>> 10

How to return a variable from a function using subprocess?

Take a look at https://stackoverflow.com/a/7975511/3930971

You are using another system process to run the script, it does not tell the rest of your system of the value returned the call to run(). All the rest of the system sees is what is directed to output (stdout, stderr), your current script only sends "running" to output, so that is what subprocess sees.

If you decided to treat it as module and import it, you could get return values of functions.

Getting the output of a python subprocess

Try checking stderr with p.communicate()[1].



Related Topics



Leave a reply



Submit