I want to ensure os.system('env')
not contain some specific variable myname
which is export in ~/.bashrc
as export myname=csj
Therefore, I wrote below python code:
import os
def print_all():
print "os.environ['myname']=%s" % os.environ.get('myname')
print "os.getenv('myname')=%s" % os.getenv('myname')
os.system('env | grep myname')
print
def delete_myname():
if 'myname' in os.environ: os.environ.pop('myname')
if os.getenv('myname'): os.unsetenv('myname')
print_all()
os.putenv('myname', 'csj2')
print "---------------------"
delete_myname()
print_all()
os.putenv('myname', 'csj3')
print "---------------------"
delete_myname()
print_all()
I think examine both os.environ['myname']
and os.getenv('myname')
and then delete them if exist,
can ensure os.system('env | grep myname')
get nothing.
However, the result is:
os.environ['myname']=csj
os.getenv('myname')=csj
myname=csj
---------------------
os.environ['myname']=None
os.getenv('myname')=None
---------------------
os.environ['myname']=None
os.getenv('myname')=None
myname=csj3
I don't understand why I still got csj3
on os.system('env | grep myname')
?
From the docs:
For
unsetenv
there is a similar warining:getenv
just returns the value fromos.environ
, as it's implementation shows, so by using it you get into a state where it seems the value isn't set when you look it up from python, while it acutally is in the real environment. The only way to get it now I can think of would be to call the c getenv function using ctypes...If i modify your code to use
os.environ
isnstead of callingputenv
/unsetenv
everything works as expected:output:
A good practice could be:
myname
environment variable (if it exists),myname
environment variable at function completion.Yu can do that easily with something like the
modified_environ
context manager describe in this question.