How to make an environment variable available for a python program using os.environ module?
I'm just new in this site and new to all the GNU/Linux environment, I'm trying to access to an environment variable from a python program that I wrote in PyCharm, I created it but I the the variable doesn`t appears in my python program.
This is what I already have done:
-created an environment variable in .bashrc (when I verify, the variable appears me in the terminal)
This is what I have typed in my .bashrc file --> export API_KEY=my_api_key_here
-import os package to my program
-use the os.environ module in my program (to check if my environment variable appears)
I don`t really know where to define my environment variables, on .bashrc or .profile files, (that two option are the only ones that appears me)
In short I want to have access to my own defined environment variables from my program.
I hope you can help me please! And tell me what I`m doing wrong.
51 Answer
In Ubuntu, you usually put it in .bashrc, because users usually use bash. If you've verified that it exists in the terminal, probably you forgot to export it. Without exporting it, it exists only in your current terminal, not in your python script nor any program you calls from the terminal.
This is an example python code named envi.py:
import os
print(os.environ['MYVAR'])First, let's test it directly in terminal:
export MYVAR="my value"
python3 envi.py
# the output should be: my valueIf you're satisfied with the result, you can then put export MYVAR="my value" in .bashrc, open a new terminal, and then run your python script.