os.putenv() has no effect

Dave Angel davea at davea.name
Tue Jun 18 14:09:11 EDT 2013


On 06/18/2013 12:49 PM, Johannes Bauer wrote:
> Hi group,
>
> I've tracked down a bug in my application to a rather strange
> phaenomenon: os.putenv() doesn't seem to have any effect on my platform
> (x86-64 Gentoo Linux, Python 3.2.3):
>
>>>> os.getenv("PATH")
> '/usr/joebin:/usr/local/bin:/usr/bin:/bin:/usr/games/bin:/usr/sbin:/sbin:~/bin'
>>>> os.putenv("PATH", "/")
>>>> os.getenv("PATH")
> '/usr/joebin:/usr/local/bin:/usr/bin:/bin:/usr/games/bin:/usr/sbin:/sbin:~/bin'
>
>
>>>> os.getenv("FOO")
>>>> os.putenv("FOO", "BAR")
>>>> os.getenv("FOO")
>>>>
>
> Does anybody know why this would happen or what I could be doing wrong?
> Help is greatly appreciated.
>

Quoting (retyping) from the getenv docs, "...however, calls to putenv() 
don't update os.environ, so it is actually preferable to assign to items 
of os.environ."

As to why, I'm not at all sure.  Only that many environments don't 
support putenv().  But why that should stop it working in the obvious 
way ?  No idea.

os.environ is not an ordinary dict, it's a "mapping object".  And among 
other things, when you modify os.environ, Python will call putenv. 
Quoting from the os.environ docs, "If the platform supports the putenv() 
function, this mapping may be used to modify the environment.  putenv() 
will be called automatically wehn the mapping is modified."

In other words, you shouldn't use putenv(), but instead modify os.environ.

-- 
DaveA



More information about the Python-list mailing list