jupyter-notebookmagic-command

I want to run magic command % somefile.py inside a jupyter notebook. However, this program requires variables from the main script


To clarify, somfile.py needs variables that are generated from main.ipynb. So, when I simply do %run somefile.py I get this error:

NameError: name 'viewer' is not defined

This viewer is defined in the main code above. However, now if I use %load somefile.py and THEN run it, it works fine. But, the whole point of me doing this is to not show the users of my script, the nitty gritty details. I am preparing this for some students.


Solution

  • The documentation of the magic command %run covers use of the -i option to "run the file in IPython’s namespace instead of an empty one." You want to add that flag to your %run command:

    viewer = "something"
    %run -i my_script.py
    

    It applies to notebook kernel namespace as IPython was incorporated into the IPython notebook, which became the Jupyter notebook project later.