[Python-ideas] How to Set Environment Variables

罗勇刚(Yonggang Luo) luoyonggang at gmail.com
Wed Mar 30 08:07:17 CEST 2011


http://code.activestate.com/recipes/159462-how-to-set-environment-variables/

Writes environment variables using a batch file wrapper. Overcomes an
operating system limitation.

*setvar.bat*
*----------*
*@echo off*
*python setvarp.py %1 %2 %3 %4 %5 %6 %7 %8 %9*
*settmp*
*del settmp.bat*
*
*
*setvarp.py*
*----------*
*import sys, time, math*
*key = sys.argv[1]*
*value = eval(' '.join(sys.argv[2:]))*
*command = 'set %s=%s\n' % (key, value)*
*open('settmp.bat', 'w').write(command)*
*
*
*
*
*sample command line session*
*---------------------------*
*C>setvar ts time.ctime()*
*C>setvar pi 22.0 / 7.0*
*C>setvar pyver sys.version*
*C>set*
*
*
*TS=Sun Oct 27 18:12:23 2002*
*PI=3.14285714286*
*PYVER=2.3a0 (#29, Oct 22 2002, 01:41:41) [MSC 32 bit (Intel)]*

Environment variables can be read with os.environ. They can be written (for
sub-shells only) using os.putenv(key, value). However, there is no direct
way to modify the global environment that the python script is running in.
The indirect method shown above writes a set command to a temporary batch
file which is in the enclosing environment by another batch file used to
launch the python script.

In the example above, arbitrary expressions can be evaluated and the result
assigned to an environment variable. For security, the eval() function can
be replaced with str().

Usually, writing to an environment variable should be avoided in favor of
sharing values through a pipe or a common data file. However, when it can't
be avoided, the above technique is an effective, though hackish,
work-around.


from page  http://docs.python.org/library/subprocess.html#subprocess.Popen,we
know the constructor for Popen is
class subprocess.Popen(args, bufsize=0, executable=None, stdin=None,
stdout=None, stderr=None, preexec_fn=None,close_fds=False, shell=False,
cwd=None, env=None, universal_newlines=False, startupinfo=None,
creationflags=0)?
we know after calling Popen, it's won't affect the parent environment, but,
with many conditions, we wan't to modify the current environment variables
by outer Bash script or DOS bash script. So I suppose to add an extra
parameter update_parent_env (Default to False), to implement such a
function.

-- 
         此致
礼
罗勇刚
Yours
    sincerely,
Yonggang Luo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110330/3159f473/attachment.html>


More information about the Python-ideas mailing list