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_dotenv
import osprint(f"value: {os.environ.get("MY_VAR")}")
value: None
from dotenv import load_dotenvload_dotenv("./.envrc")print(f"value after dotenv load: {os.environ.get("MY_VAR")}")
value after dotenv load: test_val
Quick 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...
Managing Multiple Tool Versions with Nix
This post is extremely similar to nix flakes and direnv. Here, I repeated my process, but with a little more thought and a little less language model...