Running `uv` with Environment Variables

The .env* file and the python-dotenv package are popular conventions in Python for managing environment variables. I often forget or pause when trying to remember exactly which package I need to install (python-dotenv) and how to do the import

from python_dotenv import load_dotenv
load_dotenv()

I heard someone recently lament that the package wasn’t pip install-able as pip install dotenv but fortunately, uv as a great and memorable solution to this problem that doesn’t require any changes to your code.

How?

You can use the --env-file flag to specify a .env file to load when running uv run.

script.py
import os
print(os.getenv("HELLO"))
.env
HELLO="world"

Starting by running without the --env-file flag, we see the environment variable is not loaded.

Terminal window
uv run python script.py
#=> None

Run with the --env-file flag:

Terminal window
uv run --env-file .env python script.py
#=> "world"

The uv tool also supports the UV_ENV_FILE environment variable for this purpose.

Better with direnv

Coupled with direnv, you can run all your uv commands as normal and set the environment variable such that your secrets are included.

.envrc
export UV_ENV_FILE=".env"
Terminal window
direnv allow
uv run python script.py
#=> "world"

Or you can let just let direnv load the .env file for you.

.envrc
dotenv
Terminal window
direnv allow
uv run python script.py
#=> "world"

Given all the options for loading environment variables, in the tools I am already using, there isn’t usually a good reason for me to install python-dotenv anymore.