Python environment variables

Python environment variables

python
Author

ivansaul

Published

January 5, 2023

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

MY_ENV_VAR = os.environ('MY_ENV_VAR')

From the .env file:

MY_ENV_VAR = "This is my env var content."

Resources:

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()
MY_ENV_VAR = os.environ['MY_ENV_VAR']

Resources: