When using os.execlp, why `python` needs `python`

2019-01-07 23:13发布

问题:

The code is like this:

os.execlp('python', 'python', 'child.py', #other args#)  # this works

os.execlp('python', 'child.py', #other args#)  # this doesn't work

I read this question: execlp() in python

But I'm still confused. The answer said:

The first argument is the program to execute (found on the PATH). The rest are the sys.argv arguments to the program.

However, if I run: python child.py 1 2 3 and the sys.argv of this process would be ["child.py", "1", "2", "3"], where the python doesn't exist. Then why should I add python as the second parameter of os.execlp?

回答1:

When python is executed, it creates sys.argv for you. The values in that list are based on the arguments passed to it by the operating system, but it leaves off the sys.executable value from that list.

In other words, when Python is invoked, it sets sys.argv to everything but it's own executable.

When you invoke a new executable via os.execlp(), you still need to include Python in that as that is what executable that the OS will run. The first two values of what you a pass to os.execlp() are still required, whatever you find in sys.argv later on.



回答2:

The second python is a name for python, it can be any string, but it has to be there.

See the second paragrph of http://docs.python.org/3/library/os.html?highlight=os.exec#process-management