How to set environment variables in Jupyter notebook

In some cases you would like to share some configuration information, such as API keys, database credentials etc, between different Jupyter notebooks without exposing sensitive information, you could achieve this by using environment variables.

You can create a .env file in the same directory as your Jupyter notebook on your local file system, and then load the environment variables from the .env file into your Jupyter notebook using the python-dotenv package.

Here are the steps to create a .env file and load its environment variables into your Jupyter notebook:

  1. Create a .env file in the same directory as your Jupyter notebook
touch .env
vi .env

2.  Add your environment variables to the .env file, for example if you want to set the API key of OpenAI

OPENAI_API_KEY = 'sk-................................'

3.  Install the python-dotenv package using pip:

pip3 install python-dotenv

4. Load the environment variables from the .env file into your Jupyter notebook using the load_dotenv function from the python-dotenv package.

import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

api_key  = os.environ.get('OPENAI_API_KEY')

Hope it helps,

Michael

DigitalOcean Referral Badge