简体   繁体   English

在Python中读取环境变量

[英]Read environment variables in Python

I have set some environment variables in ~/.profile : 我在~/.profile设置了一些环境变量:

SOMEVAR=/some/custom/path

and already did source ~/.profile . 并已经source ~/.profile So when I do: 因此,当我这样做时:

echo $SOMEVAR

it prints the correct directory: 它显示正确的目录:

/some/custom/path

However, when I try to read this variable in a Python script, it fails: 但是,当我尝试在Python脚本中读取此变量时,它将失败:

import os

print(os.environ["SOMEVAR"])

I get: 我得到:

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'

What's wrong there? 怎么了

You don't want the launched processes see all the crap (= variables) you've created. 您不希望启动的进程看到您创建的所有废话(=变量)。 Hence regular variables are only visible in this shell you're executing. 因此,常规变量仅在您正在执行的此shell中可见。

You have to export the variable: 您必须导出变量:

export SOMEVAR=/some/custom/path

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM