gpt4 book ai didi

Python sys.executable 为空

转载 作者:太空狗 更新时间:2023-10-30 01:06:11 28 4
gpt4 key购买 nike

我正在测试用 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(...)

之后运行的

最佳答案

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

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

关于Python sys.executable 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39254684/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com