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
Sqlalchemy: What's the Difference Between Flush() and Commit()
Meaning of Inter_Op_Parallelism_Threads and Intra_Op_Parallelism_Threads
Importerror: No Module Named Crypto.Cipher
How to Access the Previous/Next Element in a for Loop
Convolve2D Just by Using Numpy
Python Pandas: How to Specify Data Types When Reading an Excel File
Solving "Dll Load Failed: %1 Is Not a Valid Win32 Application." for Pygame
Save/Load Scipy Sparse Csr_Matrix in Portable Data Format
Conda' Is Not Recognized as Internal or External Command
Python: Call a Function from String Name
Python List Directory, Subdirectory, and Files
Take the Content of a List and Append It to Another List
Generating Matplotlib Graphs Without a Running X Server
How to Install Python 3.X and 2.X on the Same Windows Computer
The Problem with Installing Pil Using Virtualenv or Buildout