How to set and access environment variables in Python

Published

June 18, 2024

I recently presented a webinar on creating a Quarto dashboard using BLS data and deploying it to Posit Connect. The process required setting three environment variables containing sensitive information, which are needed for the script but should not be publicly shared1. See the script using the environment variables.

In Python, you can edit and access environment variables with the os and dotenv packages. Install the dotenv package (you don’t need to install os separately as it is part of the initial Python installation):

Terminal
pip install python-dotenv

In your working directory, create a .env file:

Terminal
touch .env

Open the .env file and add your environment variables using the syntax VAR_NAME="value":

.env
BLS_KEY="12345"

Save the file. Then, import the two packages in your Python script:

script.py
import os
from dotenv import load_dotenv
load_dotenv()

Refer to the environment variable in your Python script using os.environ.get():

script.py
bls_key = os.environ.get("BLS_KEY")

You can test whether it was successfully accessed:

script.py
print(bls_key)

Here’s an example of how I used it in my script:

script.py
for table_id in table_ids:
    bls_key = os.environ.get("BLS_KEY")
    parameters = json.dumps(
        {
            "registrationkey": bls_key,
            "seriesid": [table_id],
            "startyear": "2018",
            "endyear": "2024",
            "calculations": "true",
        }
    )

Be sure to add .env to your .gitignore file if using Git, so that you don’t accidentally upload your secret keys:

.gitignore
.env

Footnotes

  1. R users: we’re fortunate to have Sys.setenv() and usethis::edit_r_environ().↩︎