遇到的情形

分析的代码已经调试好,但分析的时间较长;

后端启动jupyter notebook后,奈何网络不稳定,notebook经常掉线,跑到一半的程序就断掉了;

服务器其他人的jupyter notebook的端口如果和我的一样,别人启动jupyter notebook后,我正在用的端口就会往后变。

于是我就想,能否在终端直接运行.ipynb文件,这样我就可以加nohup命令了,或者把ipynb的代码转成python,我nohup运行python也行。

基于以上情况,我google到了nbconvert。

nbconvert

nbconvert的github地址:https://github.com/jupyter/nbconvert

jupyter nbconvert通过模版引擎jinja将ipynb文件转成其他格式的文件,包括

  • HTML
  • LaTeX
  • PDF
  • Reveal JS
  • Markdown (md)
  • ReStructured Text (rst)
  • executable script

此外nbconvert还有另外一个功能就是通过–execute选项在终端执行ipynb文件

安装nbconvert

1
2
pip install nbconvert
# 或者conda install nbconvert

ipynb格式转换

1
2
3
4
5
# 转成python,转成后,后有前缀和ipynb一样的py文件,运行这个就行。
jupyter nbconvert --to python --execute mynotebook.ipynb
# --to后面跟格式,比如html
jupyter nbconvert --to html mynotebook.ipynb
# 支持的格式包括['asciidoc', 'custom', 'html', 'html_ch', 'html_embed', 'html_toc', 'html_with_lenvs', 'html_with_toclenvs', 'latex', 'latex_with_lenvs', 'markdown', 'notebook', 'pdf', 'python', 'rst', 'script', 'selectLanguage', 'slides', 'slides_with_lenvs']

上面是格式转换,在转换的过程中,比如转pdf、latex的时候,可能还需要额外的包,比如pandoc等,还需要额外安装。可以参考https://nbconvert.readthedocs.io/en/latest/index.html

jupyter nbconvert还有个功能就是执行ipynb格式的文件,如下

1
2
3
4
5
jupyter nbconvert --execute mynotebook.ipynb
# 这个时候就和linux终端下的正常命令类似了,比如加上重定向
jupyter nbconvert --execute mynotebook.ipynb >> mylog.out.log 2>&1
# 还可以和格式转换相结合
jupyter nbconvert --to python --execute mynotebook.ipynb

假设我想把通过运行jupyter nbconvert执行ipynb文件的过程更简单点,可以通过在.profile里面设置命令的别名

1
2
3
4
# .profile或者.bashrc里面配置
alias nbx="jupyter nbconvert --execute"
# 终端运行ipynb文件
nbx mynotebook.ipynb

参考

https://stackoverflow.com/questions/35545402/how-to-run-an-ipynb-jupyter-notebook-from-terminal

Github: https://github.com/jupyter/nbconvert

Document: https://nbconvert.readthedocs.io/en/latest/index.html

####################################################################

#版权所有 转载请告知 版权归作者所有 如有侵权 一经发现 必将追究其法律责任

#Author: Jason

#####################################################################