How to Set Env Variable in Jupyter Notebook

How to set env variable in Jupyter notebook

To set an env variable in a jupyter notebook, just use a % magic commands, either %env or %set_env, e.g., %env MY_VAR=MY_VALUE or %env MY_VAR MY_VALUE. (Use %env by itself to print out current environmental variables.)

See: http://ipython.readthedocs.io/en/stable/interactive/magics.html

Setting environment variables in jupyter hub

Setting environment variables from the notebook results in these variables being available only from that notebook.

%env VAR=TEST
import os
print(os.environ["VAR"])
...
>>> TEST

If you want to persist the variable, you need to put it either in the kernel.json file, or in systemd service file for jupyterhub, or in something like ~/.bashrc.

update env variable on notebook in VsCode

The terminal you open in VSC is not the same terminal ipython kernel is running. The kernel is already running in an environment that is not affected by you changing variables in another terminal. You need to set the variables in the correct environment. You can do that with dotenv, but remember to use override=True.
This seems to work:

import dotenv
from os import environ
env_file = '../.env'

f = open(env_file,'w')
f.write('MY_VAR="HELLO_ALICE"')
f.close()
dotenv.load_dotenv(env_file, override=True)
print('MY_VAR = ', environ.get('MY_VAR'))

f = open(env_file,'w')
f.write('MY_VAR="HELLO_BOB"')
f.close()
dotenv.load_dotenv(env_file, override=True)
print('MY_VAR = ', environ.get('MY_VAR'))
MY_VAR =  HELLO_ALICE
MY_VAR = HELLO_BOB

Jupyter Notebook to set environment variable from bash subprocess

You can't export variables from one bash cell to another (that isn't a child), but you can export from your Python parent process to bash.

import os, subprocess

# set a Python variable 'project'
project = subprocess.check_output(['gcloud', 'config', 'list', 'project',
'--format', 'value(core.project)'])

# Copy it to an environment variable 'PROJECT'
os.environ['PROJECT'] = project


Related Topics



Leave a reply



Submit