+-

我使用下面的 python代码来重置 Linux CentOS 6中的环境变量http_proxy,但它并没有取消其余 Python脚本的变量.
码:
import os
print "Unsetting http..."
os.system("unset http_proxy")
os.system("echo $http_proxy")
print "http is reset"
输出:
Unsetting http...
http://web-proxy.xxxx.xxxxxxx.net:8080
http is reset
Process finished with exit code 0
最佳答案
每次调用os.system()都会在自己的子shell中运行,并拥有自己的新环境:
>>> import os
>>> os.system("echo $$")
97678
0
>>> os.system("echo $$")
97679
0
您正在取消设置http_proxy变量,但是您的子shell已完成执行命令(即:unset),并终止.然后,您可以使用新环境启动一个新子shell,以运行echo.
我相信你要做的是del os.environ [‘http_proxy’]或os.environ.pop(‘http_proxy’),如果你想确保没有http_proxy环境变量,无论以前是否存在过一个:
$export foo=bar
$python2
Python 2.7.10 (default, Jul 15 2017, 17:16:57)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['foo']
'bar'
>>> del os.environ['foo']
>>> os.system('echo $foo')
0
点击查看更多相关文章
转载注明原文:linux – 如何在Python中取消设置’http_proxy’环境变量 - 乐贴网