28

I want to be able to define a variable by the return value of a script. This is what I currently have:

sum_total_earnings_usd = subprocess.call([SCRIPT, "-d", date])

I have checked the return value of SCRIPT, however, when I try and set this variable, it always returns 0 ( http://docs.python.org/library/subprocess.html#subprocess.call ). How would I run this script and capture the return value to store as a variable?

jcollado
  • 39,419
  • 8
  • 102
  • 133
David542
  • 104,438
  • 178
  • 489
  • 842

3 Answers3

41

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

wildwilhelm
  • 4,809
  • 1
  • 19
  • 24
  • Thank you. `subprocess.check_output()` is the one that runs the command and returns the return value. – David542 Jan 27 '12 at 23:05
  • If you want the output write your value to STDOUT and use `check_output()` to get the value. Otherwise, jcollado is correct that the process exit status is already returned. –  Jan 27 '12 at 23:05
  • 3
    Note that the [return value](https://en.wikipedia.org/wiki/Exit_status) is different from the program's output, which is what you are trying to get here. The return value is zero because, by convention, zero indicates that the script ran successfully and didn't have an error. The program's output is what it prints to stdout (or possibly stderr), and getting this value is achieved by redirection, just like using standard unix pipes. – wildwilhelm Apr 12 '18 at 08:08
10

If your script is returning the value, then you would want to use subprocess.check_output():

subprocess.check_output([SCRIPT, "-d", date], shell=True).

subprocess.check_call() gets the final return value from the script, and 0 generally means "the script completed successfully".

Makoto
  • 104,088
  • 27
  • 192
  • 230
3

subprocess.call already returns the process return value. If you're always getting 0, then you'll need to review SCRIPT to make sure that it's returning the value you expect.

To double check, you can also execute the SCRIPT in a shell and use $? to get the return code.

jcollado
  • 39,419
  • 8
  • 102
  • 133