edge-case
edge-case

Reputation: 1334

Pass variable from Jupyter notebook to python script

I would like to define a variable in a Jupyter notebook and then pass it to a python script.

For example, in the notebook:

a = [1, 2, 3, 4]

%run example.py
print foo

And in example.py

b = [5, 8, 9, 10]
foo = a + b

Of course, this returns an error because a has not been defined in example.py. However, if example.py has instead

a = [1, 2, 3, 4]
b = [5, 8, 9, 10]
foo = a + b

Then the Jupyter notebook can "see" foo after the script is run and print it, even though foo was not defined in the Jupyter notebook itself.

Why can't the python script see variables in the Jupyter notebook environment? And how can I pass a variable from the notebook environment to the script?

Upvotes: 4

Views: 3351

Answers (1)

Aseem Bansal
Aseem Bansal

Reputation: 6962

The python script cannot see the variables in jupyter notebook environment because they are different programs. When you use magic commands it runs as a separate program. If you want to pass the variable to the method then you have the option to convert that into a function. Say add

def add(a):
  b = [5, 8, 9, 10]
  foo = a + b

Then in Jupyter you can do this

from example import add
add(a)

You have to bring them in the same program. Otherwise you can pass the arguments and parse them in the script using argv. But I don't think you want to do that as you want them to see each other.

Upvotes: 1

Related Questions