Reputation: 113
I use python 3.6 os.environ[] to set/get variables. My question is - why the Linux command #pritenv does not show these variables? Here is the example:
[root@server ~ 508]$cat test.py
import os
os.environ['foo'] = 'bar'
print(os.environ['foo'])
[root@server ~ 509]$
[root@server ~ 509]$
[root@server ~ 509]$python3.6 test.py
bar
[root@server ~ 510]$printenv | grep foo
[root@server ~ 511]$ ((nothing))
Upvotes: 2
Views: 2705
Reputation: 72735
Environment variables modify the environment of the current process. Here's an example
% echo $SO_EXAMPLE # No value here
% bash # Start a new shell
$ SO_EXAMPLE="something"
$ echo $SO_EXAMPLE # It's available here
something
$ bash # start a new shell
$ echo $SO_EXAMPLE # Nothing here since it was not exported
$ exit # Go back to the parent shell
exit
$ export SO_EXAMPLE #Export the variable
$ bash # Start a new shell
$ echo $SO_EXAMPLE #It's visible here
something
$ exit # Go back to the parent shell
exit
$ exit # Go back to the original shell
exit
% echo $SO_EXAMPLE # Still nothing here. Even if it was exported.
So, even if you modify the environment, your parent environment won't be affected. In your case, the second is a Python process but the logic is similar.
Upvotes: 1
Reputation: 12493
What you're seeing is the result of how processes and environment variables work in Linux (and most other operating systems). Each process inherits environment variables from its parent process, but doesn't (and cannot) impact its parent's environment. Specifically, in your case you have:
printenv
, which prints all its environment variables, which are the ones it got from its parent - the shell. Upvotes: 1