简体   繁体   中英

Read environment variables in Python

I have set some environment variables in ~/.profile :

SOMEVAR=/some/custom/path

and already did 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:

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.

You have to export the variable:

export SOMEVAR=/some/custom/path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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