![](/img/trans.png)
[英]python - os.getenv and os.environ don't see environment variables of my bash shell
[英]Why can't I see environment variables, that has been set via “os.environ[]”
我使用 python 3.6 os.environ[] 來設置/獲取變量。 我的問題是 - 為什么 Linux 命令 #pritenv 不顯示這些變量? 這是示例:
[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))
您所看到的是進程和環境變量在 Linux(和大多數其他操作系統)中如何工作的結果。 每個進程都從其父進程繼承環境變量,但不會(也不能)影響其父進程的環境。 具體來說,在您的情況下,您有:
printenv
,它打印它的所有環境變量,這些環境變量是它從它的父級 - shell 那里得到的。環境變量修改當前進程的環境。 這是一個例子
% 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.
所以,即使你修改了環境,你的父環境也不會受到影響。 在您的情況下,第二個是 Python 進程,但邏輯相似。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.