daniel451
daniel451

Reputation: 11002

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?

Upvotes: 2

Views: 1667

Answers (1)

Karoly Horvath
Karoly Horvath

Reputation: 96326

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

Upvotes: 4

Related Questions