Amos
Amos

Reputation: 1274

Python script executes from terminal, but not when using subprocess?

I'm using subprocess to execute a Python script called trace.py that is located in a different folder. The script trace.py then uses subprocess to run a traceroute command and then prints the output. When I go to the folder that trace.py is located in and type this in the terminal:

python trace.py

or

./trace.py

or from any location:

python /home/.../cgi-bin/trace.py

it works fine and the traceroute is printed to the terminal. However, when I try to execute trace.py from main.py by using subprocess, it doesn't seem to work. I've tested this by creating test.py and using subprocess to execute it from main.py and this works. I do this with the following:

output = subprocess.check_output([sys.executable, script_path])

Where script_path is the absolute path to trace.py.

The full error I get is this (paths are shortened):

Traceback (most recent call last):
    File "/home/.../cgi-bin/trace.py", line 11, in <module>
traceroute = subprocess.check_output(["traceroute", "www.google.com"])
    File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
    File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
    File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
Traceback (most recent call last):
    File "main.py", line 97, in <module>
serve(args.port, public_html, cgibin)
    File "main.py", line 55, in serve
process = subprocess.check_output(["/usr/bin/python", script_path])
    File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['/usr/bin/python', '/home/.../cgi-bin/trace.py']' returned non-zero exit status 1

Why does this not work, but executing it from the terminal does?

Upvotes: 1

Views: 1323

Answers (1)

jfs
jfs

Reputation: 414079

The child can't find traceroute executable.

  1. Compare os.environ['PATH'] in your shell with the value within runnning trace.py

  2. Check file permissions -- whether it is readable and executable by the user that runs trace.py.

Upvotes: 2

Related Questions