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

2019-01-07 22:32发布

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?

2条回答
Deceive 欺骗
2楼-- · 2019-01-07 23:34

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

查看更多
【Aperson】
3楼-- · 2019-01-07 23:38

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.

查看更多
登录 后发表回答