2016-02-13 49 views
2

我在~/.profile設置一些環境變量讀取環境變量:在Python

SOMEVAR=/some/custom/path 

,並已經做了source ~/.profile。所以,當我做的:

echo $SOMEVAR 

它打印正確的目錄:

/some/custom/path 

然而,當我嘗試在Python腳本來讀取這個變量,它失敗:

import os 

print(os.environ["SOMEVAR"]) 

我得到:

Traceback (most recent call last): 
    File "environment_test.py", line 3, in <module> 
    print os.environ["SOMEVAR"] 
    File "/usr/lib64/python2.7/UserDict.py", line 23, in __getitem__ 
    raise KeyError(key) 
KeyError: 'SOMEVAR' 

w ^帽子在那裏錯了嗎?

回答

4

您不希望啓動的進程看到您創建的所有廢話(=變量)。因此,常規變量僅在您執行的shell中可見。

你要導出的變量:

export SOMEVAR=/some/custom/path 
+0

在'〜/ .profile'?但爲什麼echo $ SOMEVAR正在工作呢? – daniel451

+0

該變量存在於您的shell(源自.profile的進程)中,但不會導出到子進程(您的python腳本)。 –

+0

很好,謝謝你的解釋!我添加了'export',它現在可以運行:) – daniel451