[New-bugs-announce] [issue16633] os.environ updates only one copy of env vars under Windows (GetEnvironmentVariable vs. getenv)

Václav Šmilauer report at bugs.python.org
Fri Dec 7 13:01:43 CET 2012

New submission from Václav Šmilauer:

On windows, environment variables exist in two copies: one is manipulated using win32 API (GetEnvironmentVariable, SetEnvironmentVariable), and another one is maintained by the C runtime (getenv, _putenv). This is explained in more depth in [1].

os.environ manipulates win32 environment variables, but *not* those seen by the CRT. This means that if I set an environment variable using os.environ and later read it, in the same process, using getenv in an extension module, it will not give the expected result. Child processes *do* see those vars in CRT, since it is copied over from the win32 version at process startup.

Setting env vars has legitimate uses, since it is one of the few ways to influence initialization of extension modules: for instance, setting OMP_NUM_THREADS sets number of threads for OpenMP runtime (which cannot be changed once the module using it is loaded).

It would be ideal to keep both CRT and win32 env vars in sync transparently. If that is not realistically achievable, this gotcha should be documented as a warning in the os.environ documentation.

A workaround to this problem to set variables in both win32 and CRT using something like

    import ctypes, ctypes.util, os.environ

[1] http://msmvps.com/blogs/senthil/archive/2009/10/13/when-what-you-set-is-not-what-you-get-setenvironmentvariable-and-getenv.aspx

assignee: docs at python
components: Documentation
messages: 177081
nosy: docs at python, eudoxos
priority: normal
severity: normal
status: open
title: os.environ updates only one copy of env vars under Windows (GetEnvironmentVariable vs. getenv)
type: behavior
versions: Python 2.7, Python 3.3

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list