2

I am trying to execute a python script from another and storing the output value in a variable.

When I do this:

import os

test = os.system("/usr/local/bin/script1.py")
print test;

and then execute the script I get an extra zero on the results:

$ ./test.py
171
0

script1.py does produce "171" as the output, but not sure where the extra zero is coming from... Any ideas?

Omar Santos
  • 107
  • 1
  • 2
  • 5

3 Answers3

2

The zero is the return code from the command, which you are assigning to test and then printing. (Zero means that no error occurred.)

If you don't know what it is, why are you printing it?

kindall
  • 178,883
  • 35
  • 278
  • 309
  • Thank you! I just want to store the output of the first script in a variable. Is there any better way to do it instead of os.system()? – Omar Santos Nov 11 '13 at 19:43
  • Yes—as [the documentation](http://docs.python.org/2/library/os#os.system) says, you should be using the [`subprocess` module](http://docs.python.org/2/library/subprocess.html#module-subprocess) instead. – kindall Nov 11 '13 at 20:19
2

That's the exit status of the command.

help(os.system):

system(...)
    system(command) -> exit_status

    Execute the command (a string) in a subshell.

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.


It's better to subprocess.check_output if you want to store the output of a command in a variable.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

Something like this. I've #!'d to CPython 3.3, but 2.x should work too:

#!/usr/local/cpython-3.3/bin/python

import subprocess

test = subprocess.check_output(args=["echo", "171"])
print(test)
dstromberg
  • 6,954
  • 1
  • 26
  • 27