简体   繁体   中英

Unset environment variable in Jupyter Notebook

How do I unset an environmental variable in Jupyter Notebook? I set the variables using a .env file that is loaded by:

from dotenv import load_dotenv
load_dotenv('./.env')

After changing the .env file and rerunning the import/load does the variable stays the same (the old version). I tried setting the environment variable to None using the magic command but it's literally now None instead of blank. I didnt see any unset command at https://ipython.readthedocs.io/en/stable/interactive/magics.html

Any way to accomplish this?

TL/DR ; You can undo changes made by load_dotenv manually; by storing the original os.environ to a variable, then overwriting os.environ with it later. Alternatively, you can delete envvars with del .


Let's say you have two.env files for development and production (note that FOOGULAR_VERBOSE is defined only in .env.dev ):

.env.dev

ROOT_URL=localhost/dev
FOOGULAR_VERBOSE=True

.env.prod

ROOT_URL=example.org

You can store the base environment to an variable, then load .env.dev like such:

from dotenv import load_dotenv
import os

# Preserve the base environment before load_dotenv
base_environ = os.environ.copy()

# Then load an .env file
load_dotenv('./.env.dev')
print(os.environ)

At this stage, the envvars are:

ROOT_URL='localhost/dev'
FOOGULAR_VERBOSE='True'

To switch to the production environment, revert to the base_environ first, then load .env.prod , like this:

os.environ = base_environ  # Reset envvars
load_dotenv('./.env.prod') # Then load another .env file

Now the envvars look like this:

ROOT_URL=example.org

Another method is to delete os.environ['MY_VARIABLE'] manually, with the del statement:

del os.environ['FOOGULAR_VERBOSE']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM