Reusing code from different IPython notebooks

前端 未结 10 1201
南方客
南方客 2020-12-13 08:52

I am using IPython and want to run functions from one notebook from another (without cutting and pasting them between different notebooks). Is this possible and reasonably e

相关标签:
10条回答
  • 2020-12-13 09:20

    In IPython 2.0 you can simply %run 'my_shared_code.ipynb' to share code between notebooks. See for example http://nbviewer.ipython.org/gist/edrex/9044756.

    0 讨论(0)
  • 2020-12-13 09:23

    Starting your notebook server with:

    ipython notebook --script
    

    will save the notebooks (.ipynb) as Python scripts (.py) as well, and you will be able to import them.

    Or have a look at: http://nbviewer.ipython.org/5491090/ that contains 2 notebook, one executing the other.

    0 讨论(0)
  • 2020-12-13 09:25

    You can connect with a qtconsole to the same kernel. Just supply this at startup:

    ipython qtconsole --existing kernel-0300435c-3d07-4bb6-abda-8952e663ddb7.json
    

    Look at the output after starting the notebook for the long string.

    0 讨论(0)
  • 2020-12-13 09:29

    So @MikeMuller's good idea will work for a local notebook, but not a remote one (right?). I don't think there is a way for you to remotely invoke individual cell blocks or functions of ipynb code on a remote server and be able to get results back into your calling routine programmatically, unless that code does something fairly extraordinary to communicate results.

    I was in the process of writing when @Matt submitted the same idea about

    ipython <URI_to_Notebook> --script

    The *.pynb is a JSON container and not an actual python script. You can get ipython to export a *.py with

    If the target *.ipynb is on a remote machine you don't control, you'll probably need to pull the file so that you can write the output to a local path. (Haven't looked into whether you can invoke this on a remote resource to create a local output.) Once this is created you should be able to import and run the *.py or individual functions within it.

    A question for @Matt on that neat example of running another *.ipynb file wholesale with io.open(nbfile) is whether the nbfile can be remote? Seems like a long shot, but would be great...

    0 讨论(0)
提交回复
热议问题