Python sys.executable is empty

2024-05-08 11:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: import示例bin进程osusrsysshell