3

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

In ~/.profile? But why is echo $SOMEVAR working then?
The variable is present in your shell (the process which sourced .profile) but it is not exported to child processes (your python script).
Wonderful, thank you for the explanation! I added the export and it works now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.