Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access variable declared in a %%bash cell from another jupyter cell

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

like image 424
Alessandro Guida Avatar asked Nov 14 '18 13:11

Alessandro Guida


2 Answers

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.

like image 173
Hlib Babii Avatar answered Oct 22 '22 06:10

Hlib Babii


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']

like image 22
Marcin Avatar answered Oct 22 '22 08:10

Marcin