Save ipython notebook as script programmatically

后端 未结 2 1307
抹茶落季
抹茶落季 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条回答
  •  猫巷女王i
    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
    

提交回复
热议问题