0

I'm trying to access environment variable which is exported in ~/.bashrc file as below.

export ENV=local and did source ~/.bashrc. I can see the value local when I hit echo $ENV in terminal.

But in my python project (which is attached to a specific virtualenv in Pycharm) , when I try to do os.environ['ENV'] and run the script by rigt-clicking it and Run, it is throwing KeyError.

I can't see the ENV in the output when i try to do os.environ.

What could be the issue? I guess the virtualenv should not cause any issue. Is it true?

OS: Ubuntu 18.04
Python: 3.7.4
Underoos
  • 4,708
  • 8
  • 42
  • 85
  • I think your method of adding environment variable to the bashrc might be wrong, because if you try `os.environ` in python it would list some variables and try any of that variable you wouldn't get error – amrs-tech Sep 27 '19 at 11:37
  • So. where do I export environment variable so that I can access it from python? – Underoos Sep 27 '19 at 11:38
  • You can better try another way to add environment variable like opening the **bashrc** file and add it directly and then try with `os.environ[..]` in python – amrs-tech Sep 27 '19 at 11:38
  • That's what I did. Opened `bashrc` and added the variable as `export ENV=local`. – Underoos Sep 27 '19 at 11:39
  • Try the solution from this link : https://askubuntu.com/questions/58814/how-do-i-add-environment-variables – amrs-tech Sep 27 '19 at 11:40

2 Answers2

0

It turned out that everytime I right click and run the script in Pycharm, it was creating a RunConfiguration which contains only one ENVIRONMENT variable which is PYTHONBUFFERED=1.

And I was not able to access any of the other variables. Short term resolution is that I added the environment variable ENV=local in that RunConfiguration.

and it worked.

Underoos
  • 4,708
  • 8
  • 42
  • 85
-1

Try this:

export ENV="local"

Add this line to the last of the file ~/.bashrc file and then restart the terminal to open python.

Now:

import os
os.environ['ENV']

It would work with expected output. Hope it helps :)

amrs-tech
  • 485
  • 2
  • 14