convert json ipython notebook(.ipynb) to .py file

2020-01-29 03:47发布

How do you convert an IPython notebook file (json with .ipynb extension) into a regular .py module?

8条回答
趁早两清
2楼-- · 2020-01-29 04:51

You definitely can achieve that with nbconvert using the following command:

jupyter nbconvert --to python while.ipynb 

However, having used it personally I would advise against it for several reasons:

  1. It's one thing to be able to convert to simple Python code and another to have all the right abstractions, classes access and methods set up. If the whole point of you converting your notebook code to Python is getting to a state where your code and notebooks are maintainable for the long run, then nbconvert alone will not suffice. The only way to do that is by manually going through the codebase.
  2. Notebooks inherently promote writing code which is not maintainable (https://docs.google.com/presentation/d/1n2RlMdmv1p25Xy5thJUhkKGvjtV-dkAIsUXP-AL4ffI/edit#slide=id.g3d7fe085e7_0_21). Using nbconvert on top might just prove to be a bandaid. Specific examples of where it promotes not-so-maintainable code are imports might be sprayed throughout, hard coded paths are not in one simple place to view, class abstractions might not be present, etc.
  3. nbconvert still mixes execution code and library code.
  4. Comments are still not present (probably were not in the notebook).
  5. There is still a lack of unit tests etc.

So to summarize, there is not good way to out of the box convert python notebooks to maintainable, robust python modularized code, the only way is to manually do surgery.

查看更多
劳资没心,怎么记你
3楼-- · 2020-01-29 04:51

Jupytext allows for such a conversion on the command line, and importantly you can go back again from the script to a notebook (even an executed notebook). See here.

查看更多
登录 后发表回答