3

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?

false_azure
  • 1,333
  • 4
  • 25
  • 46
  • 1
    possible duplicate of [Store output of subprocess.Popen call in a string](http://stackoverflow.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string) – Nir Alfasi Nov 23 '14 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 Nov 23 '14 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 Nov 23 '14 at 23:15

1 Answers1

7

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)
Savir
  • 17,568
  • 15
  • 82
  • 136
  • Thank you! Wow I assumed there might be a less straight forward, more 'correct' way to do it but at least this is simple! (I'll accept this answer when it lets me) – false_azure Nov 23 '14 at 22:49
  • So do I just have my subprocess print() / sys.stdout.write() its 3 return values? – false_azure Nov 23 '14 at 22:51
  • 1
    Yeah, either way (`print` will output a newline at the end... `stdout.write` won't) – Savir Nov 23 '14 at 22:52