perl - python override environment variable in local scope -
how can override environment variable in local scope? know how in perl, not python.
in perl:
if (1) { local $env{path} = "/usr/bin:/bin:/usr/sbin:/sbin"; print "$env{path}\n"; } print "$env{path}\n";
the output be:
/usr/bin:/bin:/usr/sbin:/sbin /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
any idea how same in python?
well, 1 way save environment variable before scope starts , retrieve when ends. wonder if there nicer way that.
using python's with
statement:
from sys import argv import os class mypath(object): def __init__(self, newpath): self.newpath = newpath def __enter__(self): self.path = os.environ['path'] os.environ['path'] = self.newpath return self.newpath def __exit__(self, type, value, traceback): os.environ['path'] = self.path if __name__ == "__main__": if len(argv) < 2: print "usage: %s path" % (argv[0],) exit(1) print os.environ['path'] mypath(argv[1]) newpath: print newpath print os.environ['path'] print os.environ['path']
python path.py whatever
produces:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games whatever whatever /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
Comments
Post a Comment