Python sys.executable为空

时间:2016-08-31 16:28:25

标签: python execve

我正在测试用os.execve和虚拟环境做一些恶作剧。如果我用另一个python子进程替换当前的python进程,我遇到sys.executable为空的问题。

下面的例子显示了正在发生的事情(在python shell中运行):

import os, sys
print(sys.executable) # works this time
os.execve("/usr/bin/python", [], {}) # drops me into a new python shell
import sys # yes, again
print(sys.executable) # is empty

我在python shell中运行上述命令的完整输出:

 lptp [ tmp ]: python
Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> print(sys.executable) # works this time
/usr/bin/python
>>> os.execve("/usr/bin/python", [], {}) # drops me into a new python shell
Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys # yes, again
>>> print(sys.executable) # is empty

>>>

sys.executable为空会导致我出现问题,最明显的是platform.libc_ver()失败,因为sys.executable为空:

>>> import platform
>>> platform.libc_ver()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/platform.py", line 163, in libc_ver
    f = open(executable,'rb')
IOError: [Errno 21] Is a directory: '/tmp'

请注意,上面的示例是在调用os.execve(...)

后运行的

1 个答案:

答案 0 :(得分:5)

Python依赖于argv[0]和几个环境变量来确定sys.executable。当您传递空的argv和环境时,Python不知道如何确定其路径。至少,您应该提供argv[0]

os.execve('/usr/bin/python', ['/usr/bin/python'], {})