7

Set environment variables inside a Jupyter notebook

 3 years ago
source link: https://ericmjl.github.io/blog/2021/5/14/set-environment-variables-inside-a-jupyter-notebook/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Set environment variables inside a Jupyter notebook

written by Eric J. Ma on 2021-05-14

| tags: til jupyter data science

Today, I learned that one can set an environment variable from within a Jupyter notebook session.

Let's say you needed an environment variable set for your Jupyter notebook, but you:

  1. Don't want it set globally or project-wide, or
  2. Forgot to set it before you launched Jupyter.

To do so, add the following line(s) to the very, very first cell of the notebook:

%env MY_ENV_VAR=value

Within the same code cell, you can clone that as many times as you want to set environment variables of any kind.

To verify that the environment variable has been set correctly, you can use the following code block to view the value of the environment variable that you set:

import os
os.environ["MY_ENV_VAR"]

Now, one thing has to be stated - according to 12 Factor App development principles, you might need to set environment variables for sensitive information. You should never, ever, ever set those environment variables at the top of your notebook because they will be exposed!

I send out a monthly newsletter with tips and tools for data scientists. Come check it out at Substack.

If you would like to receive deeper, in-depth content as an early subscriber, come support me on Patreon!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK