若要仅为调用的脚本取消设置环境变量,也可以执行以下操作。os.unsetenv('PYTHONHOME')

更新:

如果必须为流的其余部分删除环境,则os.environ.pop('PYTHONHOME')或del os.environ['PYTHONHOME']更好。但是,如果您只想为在末尾分叉的脚本取消设置环境变量,那么os.unsetenv('PYTHONHOME')工作得更好,因为它仍然将环境变量保留在当前流程环境中。但是,它也将取决于如何调用脚本。

Python说Unset (delete) the environment variable named key. Such changes to the
environment affect subprocesses started with os.system(), popen() or
fork() and execv().

请参阅下面的示例。

示例脚本

(/tmp/env.py)import os
print os.environ["VIFI"]

现在让我们看看下面的内容。

vifi-a01:~ vifi$ python
Python 2.7.16 (default, Oct 16 2019, 00:34:56)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> 'VIFI' in os.environ # EnvVar not present initially.
False
>>> os.environ['VIFI'] = 'V' # set the env var
>>> os.system('python /tmp/env.py') # child process/script gets it
V
0
>>> os.unsetenv('VIFI') # unset env only for child script
>>> os.system('python /tmp/env.py')
Traceback (most recent call last):
File "/tmp/env.py", line 2, in 
print os.environ["VIFI"]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 40, in __getitem__
raise KeyError(key)
KeyError: 'VIFI'
256
>>> 'VIFI' in os.environ # rest of the flow still has it
True
>>> os.environ['VIFI'] = 'V' # set it again for child process/script
>>> os.system('python /tmp/env.py')
V
0
>>>
>>> os.environ["VIFI"] = "V"
>>> ^D
vifi-a01:~ vifi$ echo $VIFI
vifi-a01:~ vifi$ printenv | grep "VIFI"
vifi-a01:~ vifi$

顺便说一句,通过os.environ设置环境只对设置它的进程(及其子进程)是本地的。它对全局环境变量没有影响,正如您在最后看到的。