2017-09-20 9 views

回答

1

你需要确保你的环境变量是持久下面你的shell重新启动,否则您的新的环境变量将无法访问以后

[email protected]:/var/tmp$ export NEWVAR='alan' 
[email protected]:/var/tmp$ python test.py 
alan 
*closes shell and reopens* 
[email protected]:/var/tmp$ python test.py 
Please set the environment variable NEWVAR 

更新您的$HOME/.bashrc/etc/environment与变量,而不是仅仅做一个setxexport

注:如果更新/etc/environment您将需要重新启动计算机以将环境变量设置在您的shell中

+0

因为我使用Windows系统可以ü请告诉我在哪里可以永久设置环境变量(路径)。我在事先添加系统设置,即使然后我面临的问题:( –

+1

我重新启动系统它现在工作正常... :) –

0

而不是使用setx来设置这些环境变量;尝试使用EXPORT。下面的例子为我工作。

export MYCUSTOMVAR="testing123" 
python testing.py 

注意:如果您在Windows上,则可以使用SET设置env变量。

SET MYCUSTOMVAR=testing123 

testing.py

import os 

if __name__ == '__main__': 
    print("MYCUSTOMVAR: {0}".format(os.environ['MYCUSTOMVAR'])) 

输出

MYCUSTOMVAR: testing123 
+0

感谢您的答复凯尔我手动添加环境变量在高级系统设置是好的?因为出口在我的系统上无法工作,即使手动添加也无法访问它 –

+0

听起来像你在Windows上。如果您需要使用SET命令,因为EXPORT在Windows上不存在。查看与Windows上的SET命令相关的此前一个问题[here](https://stackoverflow.com/questions/18701783/windows-equivalent-of-export) – Kyle

0

如果您想通过脚本来设置环境变量:

import os 
os.environ["JAVA_HOME"] = "somepath" 

如果您使用命令提示符它,它设置将只可用于fo那个外壳。如果您在高级系统设置中设置它,它将在每一处都可用,但在python脚本中打开一个新的shell时不可用。

+1

'setx'永久设置环境变量。 [SS64参考](https://ss64.com/nt/setx.html) – SitiSchu