我正在测试使用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.execve("/usr/bin/python", [], os.environ )
? - Padraic Cunninghamenv -i
遇到了类似的问题,例如env -i python /usr/local/lib/python2.7/dist-packages/virtualenv.py ~/jenkins/workspace/analysis_super__Python_tests/venv
,在这种情况下,virtualenv.py没有有效的sys.executable。 - sageenv -i
比OP的execve问题更容易解决。而env -i python -c 'import sys ; print(sys.executable)'
会得到一个空结果,只需使用完整路径env -i /usr/bin/python -c 'import sys ; print(sys.executable)'
即可得到预期结果。 - sage