Environment Variables in Python

Anh-Thi Dinh

Get

1import os
2os.environ['USER']
3os.environ.get('USER')
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

Set

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