Python environment variables
Python environment variables
python
Interacting With Environment Variables in Python for App Configuration and Secrets.
Reading .env file
Use Python dotenv Library. Just install the library, create a .env
file with your environment variables, and import the environment variables in your code like this:
pip install python-dotenv
import os
from dotenv import load_dotenv
load_dotenv()
= os.environ('MY_ENV_VAR') MY_ENV_VAR
From the .env file:
MY_ENV_VAR = "This is my env var content."
Resources:
https://towardsdatascience.com/environment-variables-python-aecb9bf01b85
Accessing GitHub secrets
Add a new secret, go to your GitHub repository > Settings > Secrets > New Repository Secret
.
Once added, you can then map them as environment variables in your GitHub actions workflow.
- name: Render Custom Richlink Shortcode
env:
MY_ENV_VAR: ${{ secrets.MY_ENV_VAR }}
run: python your_script.py
Finally, you can use them in Python as follows:
load_dotenv()= os.environ['MY_ENV_VAR'] MY_ENV_VAR
Resources:
https://medium.datadriveninvestor.com/accessing-github-secrets-in-python-d3e758d8089b