Save ipython notebook as script programmatically

后端 未结 2 1278
抹茶落季
抹茶落季 2021-01-06 17:19

The excellent ipython notebook has a handy --script command line flag that automatically saves a copy of the notebook as a .py script file (removin

相关标签:
2条回答
  • 2021-01-06 17:55

    Better yet (at least for my purposes): ipython respects local copies of the ipython_notebook_config.py file. So I can just add

    c = get_config()
    c.NotebookManager.save_script = True
    

    to such a file in my notebook directory. Apparently, ipython first reads ~/.ipython/profile_default/ipython_notebook_config.py, and then reads the local copy of that file. So it's safe to use without worrying about demolishing the user settings.

    This was not at all clear to me from the documentation, but I just tried it and it worked.

    0 讨论(0)
  • 2021-01-06 18:05

    Oh. My mistake. nbconvert can handle conversions to script. So I can do something like this:

    !ipython nbconvert --to python MyNB.ipynb
    

    Of course, this line will get saved to the script, which means the script will try to re-save the notebook to itself every time it's executed. That's a bit circular, and I can imagine it could cause problems with some of my more outlandish hacks. Instead, we can ensure that it's only run from ipython by wrapping it as follows:

    try :
        if(__IPYTHON__) :
            !ipython nbconvert --to python MyNB.ipynb
    except NameError :
        pass
    

    Note that the conversion process will automatically convert the ! syntax to something that is acceptable to plain python. This is apparently not the case with the --script conversion. So the extra-safe way to do this is

    try :
        if(__IPYTHON__) :
            get_ipython().system(u'ipython nbconvert --to python MyNB.ipynb')
    except NameError :
        pass
    
    0 讨论(0)
提交回复
热议问题