Python的sys.executable为空。

18

我正在测试使用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(...)之后运行的。


如果您将os.environ作为env传递,会发生什么 os.execve("/usr/bin/python", [], os.environ ) - Padraic Cunningham
嗯,那个可以用...但只是在我上面简化的例子中有效。在我的真实代码中并没有什么区别,因为我已经传入了当前环境的修改版本。我会更新我的问题并提供更好的例子。 - d0c_s4vage
如果sys.executable为None或空字符串,则无法找到它,因此这肯定与将空字典作为env参数有关。 - Padraic Cunningham
我在运行Python时使用env -i遇到了类似的问题,例如env -i python /usr/local/lib/python2.7/dist-packages/virtualenv.py ~/jenkins/workspace/analysis_super__Python_tests/venv,在这种情况下,virtualenv.py没有有效的sys.executable。 - sage
深入探究后,我发现使用env -i比OP的execve问题更容易解决。而env -i python -c 'import sys ; print(sys.executable)'会得到一个空结果,只需使用完整路径env -i /usr/bin/python -c 'import sys ; print(sys.executable)'即可得到预期结果。 - sage
1个回答

12

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接