2

I have a requirement where 1 process sets a value as environment variable and I read that value in python using

os.environ

As per python doc:

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

My problem is the process set/change the variable every time it calls the python script.
Please tell me a way to read the changed value.

Thanks,

shashuec
  • 684
  • 8
  • 20

2 Answers2

3

I guess you can use os.getenv() to get the value of an environment variable any time, and this will reflect the most up-to-date state.

Update: note that there is no such thing as one "global" environment, at least not on Linux. Quoting Wikipedia:

In all Unix and Unix-like systems, each process has its own private set of environment variables. By default, when a process is created it inherits a duplicate environment of its parent process, except for explicit changes made by the parent when it creates the child.

Therefore, if you launch (fork) two processes from the same parent process (such as bash), and change an environment variable in one of the processes, the other process won't see it because it uses another copy of the environment of the parent process. Similarly, if you change the environment in the parent process after having launched the child processes, the child processes won't see the change because they have already created their private copy of the environment.

Tamás
  • 47,239
  • 12
  • 105
  • 124
  • Okay. The problem is that there is no such thing as one "global" environment that is seen by all the processes. See my update above. – Tamás May 09 '11 at 11:29
  • A suggestion: you can make/re-write your process in order to restore the modified environment variables at completion by using the `modified_environ` context manager describe in this [question](http://stackoverflow.com/a/34333710/1513933). – Laurent LAPORTE May 10 '17 at 20:06
1

If your process sets/updates an environment variable and then calls the Python script, you would see the updated value in your Python script. But if these are parallel processes and the environment variable gets modified when the Python script is running then the updates to the environemnt variable is not seen in the Python script.

sateesh
  • 27,947
  • 7
  • 36
  • 45
  • I have second case.Is there any way to get the updated value? – shashuec May 09 '11 at 10:46
  • @Shashwat As I see it you would need some form of IPC for the process which spawned Python script to communicate (to Python script) modification. – sateesh May 09 '11 at 10:56