8

In a jupyter notebook I have a bash jupyter cell as follows:

%%bash

export MYVAR="something"

I would like to access $MYVAR in a different python cell. For example

print(MYVAR)

I would expect the cell to print "something", but I get a NameError message.

Example image: enter image description here

2 Answers2

6

You can try capturing the output to a python variable:

In [1]:

%%bash --out my_var

MYVAR="something"
echo "$MYVAR"

In [2]:

print(my_var)
something

Also, you might find this blog post useful.

Hlib Babii
  • 599
  • 1
  • 7
  • 24
1

One workaround is to store the output of variable from bash cell into a temp file, and then read it in python cell or other bash cell. For example

Bash cell

%%bash
my_var="some variable"

echo $my_var > /tmp/my_var

Python cell

my_var = !cat /tmp/my_var
print(my_var)

Output is: ['some variable']

Marcin
  • 215,873
  • 14
  • 235
  • 294