[python-win32] regarding invoking command prompt using python
Tim Roberts
timr at probo.com
Thu Jun 18 18:33:13 CEST 2009
Vernon Cole wrote:
> Tim:
> Okay, explain this...
> C:\BZR\sterling\HL7>c:\python26\python.exe
> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import os
> >>> os.putenv('x','test')
> >>> print os.getenv('x')
> zzz
> >>> exit()
>
> C:\BZR\sterling\HL7>set x
> x=zzz
>
> C:\BZR\sterling\HL7>
Depending on your point of view, that's either a usage problem or a
design flaw in the "os" module. On Windows, os.putenv actually calls
the operating system service that changes the current environment, but
os.getenv does not: it just reads from the os.environ dictionary, which
is a snapshot of the environment taken at startup time.. If you had
changed the variable by saying this:
os.environ['x'] = 'test'
(which is the Pythonic way to do it), you'd find that both the process
environment and Python's snapshot of the environment were updated, and
things would work as I said. By calling os.putenv, the process
environment is updated, but the Python snapshot is bypassed. You can
see that os.putenv really does update the current process environment:
C:\tmp>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, win32api
>>> os.environ['x']
'zzz'
>>> os.getenv('x')
'zzz'
>>> win32api.GetEnvironmentVariable('x')
'zzz'
>>> os.putenv('x','test')
>>> os.environ['x']
'zzz'
>>> os.getenv('x')
'zzz'
>>> win32api.GetEnvironmentVariable('x')
'test'
>>> os.system('set x')
x=test
0
>>>
Compare this to:
C:\tmp>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, win32api
>>> os.environ['x']
'zzz'
>>> os.environ['x'] = 'test'
>>> os.environ['x']
'test'
>>> os.getenv('x')
'test'
>>> win32api.GetEnvironmentVariable('x')
'test'
>>> os.system('set x')
x=test
0
>>>
The takeaway here is, basically, don't ever call os.putenv. Instead,
use os.environ.
--
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the python-win32
mailing list