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
5
  • 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 Commented Sep 27, 2019 at 11:37
  • So. where do I export environment variable so that I can access it from python? Commented Sep 27, 2019 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 Commented Sep 27, 2019 at 11:38
  • That's what I did. Opened bashrc and added the variable as export ENV=local. Commented Sep 27, 2019 at 11:39
  • Try the solution from this link : askubuntu.com/questions/58814/… Commented Sep 27, 2019 at 11:40

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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 :)

11 Comments

Turned out that the issue is because of Pycharm. I was able to run the script normally and receiving accessing the variable.
Okay, because I tried the same way inside my virtualenv and it worked, that's why suggested this answers again (sorry if it is redundant)
Did the problem solved or still it exists ? @SukumarRdjf
Not if I run the script directly. But in Pycharm, yes.
Can you reproduce your code, so that I may help ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.