This may be a stupid question but I have a Python script that starts a subprocess (also a Python script) and I need that subprocess to return three integers. How do I get those return values from the Python script that starts the subprocess? Do I have to output the integers to stdout and then use the check_output() function?
-
1possible duplicate of Store output of subprocess.Popen call in a stringNir Alfasi– Nir Alfasi2014-11-23 22:44:35 +00:00Commented Nov 23, 2014 at 22:44
-
Cheers, I know how to get output back from a subprocess - that answer you linked to is good or I could use subprocess.check_output(). In terms of passing back output from a python script running as a subprocess, is it common practice just to write the return values to stdout() and get them back in that manner?false_azure– false_azure2014-11-23 22:48:15 +00:00Commented Nov 23, 2014 at 22:48
-
If you're forking out python jobs, then perhaps the multiprocesssing module is a better fit? (especially the Pool functions like multiprocessing.Pool.map)thebjorn– thebjorn2014-11-23 23:15:28 +00:00Commented Nov 23, 2014 at 23:15
1 Answer
The answer is Yes... I want my +15 reputation!! :-D
No, seriously... Once you start dealing with subprocesses, the only way you really have to communicate with them is through files (which is what stdout, stderr and such are, in the end)
So what you're gonna have to do is grab the output and check what happened (and maybe the spawned process' exit_code, which will be zero if everything goes well) Bear in mind that the contents of stdout (which is what you'll get with the check_output function) is an string. So in order to get the three items, you'll have to split that string somehow...
For instance:
import subprocess
output = subprocess.check_output(["echo", "1", "2", "3"])
print "Output: %s" % output
int1, int2, int3 = output.split(' ')
print "%s, %s, %s" % (int1, int2, int3)
3 Comments
print will output a newline at the end... stdout.write won't)