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
.
import os
print(os.getenv("HELLO"))
HELLO="world"
Starting by running without the --env-file
flag, we see the environment variable is not loaded.
uv run python script.py#=> None
Run with the --env-file
flag:
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.
export UV_ENV_FILE=".env"
direnv allowuv run python script.py#=> "world"
Or you can let just let direnv
load the .env
file for you.
dotenv
direnv allowuv 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.
Recommended
Accessing direnv environment variables in a Jupyter notebook
I use direnv to manage my shell environment for projects. When using a Jupyter notebook within a project, I realized that the environment variables...
Nix and Direnv with Flakes
Last year I wrote about nix and direnv as I explored the potential convenience of an isolated, project-specific environment. There were some...
Nix and direnv
I know a little about nix. Not a lot. I know some things about Python virtual environments, asdf and a few things about package managers. I've heard...