Linux – How to unset the ‘http_proxy’ environment variable in Python

environment-variableslinuxPROXYpython

I am using below python code to reset the environment variable http_proxy in Linux CentOS 6, but it is not unsetting the variable for the rest of the Python script.

Code:

 import os 
 print "Unsetting http..." 
 os.system("unset http_proxy") 
 os.system("echo $http_proxy") 
 print "http is reset"

Output:

Unsetting http...
http://web-proxy.xxxx.xxxxxxx.net:8080
http is reset
Process finished with exit code 0

Best Answer

Each invocation of os.system() runs in its own subshell, with its own fresh environment:

>>> import os
>>> os.system("echo $$")
97678
0
>>> os.system("echo $$")
97679
0

You are unsetting the http_proxy variable, but then your subshell has completed executing the command (to wit: unset), and terminates. You then start a new subshell with a new environment in which to run echo.

I believe what you are trying to do is del os.environ['http_proxy'], or os.environ.pop('http_proxy') if you want to ensure there is no http_proxy environment variable whether or not one previously existed:

$ 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
Related Question