4

I am attempting to execute a BASH script which sets needed environmental variables from within a Jupyter notebook. I understand that the magic command %env can accomplish this, but the BASH script is needed in this instance. Neither the use of !source or %system accomplishes the goal of making the environmental variables persist within the Jupyter notebook. Can this be done?

2
  • I'm not clear what you mean by "persist". Do you mean they stay set across reboots? Or they stay set between different notebooks? Or they stay set from one cell to the next? What are you trying to do, please? Commented Apr 2, 2021 at 7:24
  • An option for 2025 onward, see Jeremy Howard's pshnb - "pshnb adds %psh and %%psh functions to Jupyter and IPython, which execute expressions in a persistent shell". ... "With %psh, you can implement, and document in notebooks, multi-step stateful shell interactions, including setting environment variables, sourcing scripts, and changing directories." Commented Apr 9 at 15:51

2 Answers 2

3

To permanently set a variable (eg. a key) you can set a Bash environment variable for your Jupyter notebooks by creating or editing a startup config file in the IPython startup directory.

cd ~/.ipython/profile_default/startup/
vim my_startup_file.py

The file will be run on Jupyter startup (see the README in the same directory). Here is what the startup .py file should contain:

  1 import os
  2 os.environ['AWS_ACCESS_KEY_ID']='insert_your_key_here'
  3 os.environ['AWS_SECRET_ACCESS_KEY']='another_key'

Now inside a Jupyter notebook you can call these environment variables, eg.

#Inside a Jupyter Notebook cell
import os
session = boto3.session.Session( 
    aws_access_key_id=os.getenv('AWS_ACCESS_KEY_ID'), 
    aws_secret_access_key=os.getenv('AWS_SECRET_ACCESS_KEY'),
    region_name='us-east-1'
) 

You will need to restart your kernel for the changes to be created.

Sign up to request clarification or add additional context in comments.

Comments

2

You could use python to update os variables:

Cell

! echo "export test1=\"This is the test 1\"" > test.sh
! echo "export test2=\"This is the test 2\"" >> test.sh
! cat test.sh

Result

export test1="This is the test 1"
export test2="This is the test 2"

Cell (taken from set environment variable in python script)

import os

with open('test.sh') as f:
    os.environ.update(
        line.replace('export ', '', 1).strip().split('=', 1) for line in f
        if 'export' in line
)

! echo $test1 
! echo $test2

Result

"This is the test 1"
"This is the test 2"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.