[Python-ideas] How to Set Environment Variables

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


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

*@echo off*
*python setvarp.py %1 %2 %3 %4 %5 %6 %7 %8 %9*
*del settmp.bat*
*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*
*TS=Sun Oct 27 18:12:23 2002*
*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,

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,
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

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