4

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?

1 Answer 1

1

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.

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

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.