簡體   English   中英

為什么我看不到通過“os.environ[]”設置的環境變量

[英]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(和大多數其他操作系統)中如何工作的結果。 每個進程都從其父進程繼承環境變量,但不會(也不能)影響其父進程的環境。 具體來說,在您的情況下,您有:

  • sh(或其他一些shell),帶有一些環境變量(例如X、Y、Z)。
    • Python,它創建一個新的環境變量'foo',然后死掉。
    • 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM