Hubro
Hubro

Reputation: 59343

Why doesn't Python's os.exec* functions pass any arguments?

I want to replace the current process with a new process using the same Python interpreter, but with a new script. I have tried using os.execl, which seemed like the most intuitive approach:

print(sys.executable, script_path, *args)
os.execl(sys.executable, script_path, *args)

The result is that this is printed to the screen (from the print function):

/home/tomas/.pyenv/versions/3.4.1/bin/python script.py arg1 arg2 arg3

And the Python interactive interpreter is launched. Entering this into the interpreter:

>>> import sys
>>> print(sys.argv)
['']

Shows that Python received no arguments.

If I copy the output of the print function and enter it into my terminal, it works as expected. I have also tried using execv and execlp with identical results.


Why doesn't the execl call pass the arguments to the Python executable?

Upvotes: 0

Views: 840

Answers (1)

falsetru
falsetru

Reputation: 369124

The arg0, arg1, arg2, ... (arguments after the sys.executable) are passed to subprogram as argv. If you pass script_path as a the first argument the subprogram will interpret script_path as argv[0] instead of sys.executable.

Replace the execl line as following will solve your problem:

os.execl(sys.executable, sys.executable, script_path, *args)
                         ^^^^^^^^^^^^^^

Upvotes: 2

Related Questions