Thi Notes
AboutNotesBlogTopicsToolsReading
About|Sketches |Cooking |Cafe icon Support Thi

Environment Variables in Python

Environment Variables in Python

Anh-Thi Dinh
Python

Get

1import os
2os.environ['USER']
3os.environ.get('USER')

Set

In python itself,
In terminal (we have to retype whenever we use),
In .bashrc or .zshrc (we don’t have to retype whenever we use),
Store in a file (Don’t forget to ignore this file from git) → then use python-dotenv.
 
1# from .env
2# pip install python-dotenv
3from dotenv import load_dotenv
4load_dotenv()
5# .env file doesn't need to be in the same folder of the jupyter notebook, for example
1os.environ['USER'] = 'New User'
1export USER='new user'
2# check
3echo $USER
1export USER='new user'
2
3# Don't forget to "refresh" the current bash
4source ~/.zshrc
5source ~/.bashrc
1# .env
2USER='new user'