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 in my .envrc file were not being made available to my notebooks.
The following worked for me as a low-effort way to load my environment into the notebook in a way that wouldn’t risk secrets being committed to source control, since I gitignore the .envrc file.
The code below assumes an .envrc file exists in the project root, containing
export MY_VAR="test_val"Let’s run the example
%pip install python_dotenvimport osprint(f"value: {os.environ.get("MY_VAR")}")value: Nonefrom dotenv import load_dotenvload_dotenv("./.envrc")print(f"value after dotenv load: {os.environ.get("MY_VAR")}")value after dotenv load: test_valQuick and easy!
Recommended
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...
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...
Direnv env var additions, overrides, and removals
I use direnv to overlay folder specific configurations in projects when I cd into them.
Subscribe
Get notified when I publish new posts. No spam, unsubscribe anytime.