How to Set and List Environmental Variable in Jupyter Notebook

In this short guide, you’ll see how to **set environmental variables in Jupyter Notebook and JupyterLab. **

Below you can find most popular options:

(1) Jupyter magic commands

%env AWS_KEY=XXX

(2) Setup environment variables

import os
os.environ['AWS_KEY'] = "XXX"

You will see multiple ways to set variables. Which one you are going to use will depend on your case.

Step 1: Set Environmental Variable with Jupyter Magic

First and simplest option to set environment variables in Jupyter Notebook and JupyterLab is to use magic functions.

There two types of magic commands:

  • cell magic commands (start with %%)
  • line magic commands (start with %)

To find more about the magic commands check this out: Built-in magic commands

List all Environment Variable

To list all environmental variables in Jupyter Notebook and JupyterLab with magic you can use:

%env

result of this command is a dictionary in the form of:

 'JPY_PARENT_PID': '4217',
 'CLICOLOR': '1',
 'PAGER': 'cat',
 'GIT_PAGER': 'cat',
 'MPLBACKEND': 'module://ipykernel.pylab.backend_inline',
 'AWS_KEY': 'XXX'}

Set new Environmental Variable in Jupyter

Setting new variable or new value for existing environmental variable can be done by command:

%env AWS_KEY=XXX

Note: If you use quotes like:

%env AWS_KEY="XXX"

they will be included in the value:

'MY_VAR': '"MY_VALUE"'}

Step 2: Set Environmental Variable with Jupyter Magic

The second option is to use: os.environ['AWS_KEY']. The difference between this one and the Jupyter magic is the quotes.

Set new Environmental Variable in Jupyter with os.environ

So if you need to use quotes you can use this one. You need to import the os module and use command like:

import os
os.environ['AWS_KEY'] = "XXX"

List Environmental Variables in Jupyter with os.environ

To list all or some environmental variables with os.environ. You can use this syntax:

import os
os.environ

Share Tweet Send
0 Comments
Loading...
You've successfully subscribed to SoftHints - Python, Data Science and Linux Tutorials
Great! Next, complete checkout for full access to SoftHints - Python, Data Science and Linux Tutorials
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.