Alessandro Guida
Alessandro Guida

Reputation: 195

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

Upvotes: 8

Views: 563

Answers (2)

Marcin
Marcin

Reputation: 238061

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

Upvotes: 1

Hlib Babii
Hlib Babii

Reputation: 680

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.

Upvotes: 6

Related Questions