Apologies if it has already been asked, or if the solution is trivially simple.
Using Jupyter Notebook for Python scripting. When I download a notebook as a .py file (by clicking on File->Download as->Python (.py)), Jupyter adds a bunch of extraneous commented lines. It adds some interpreter shebang, encoding declaration at the beginning, and then #In[], #Out[]
for each cell etc. To make matters more troublesome, the shebang looks like
#!/usr/bin/env python
even though I am using a python3 kernel.
While I am sure it has the best intentions, very often I want to have my own interpreter directive and skip the other commented lines altogether since they do nothing but adding to the clutter.
How to download just the raw codes, only with comments that I inserted, and cells separated by nothing but line breaks? Also, I would like to know a permanent solution to change the configuration to download it this way, for all ipynb files on my machine, not a one time commmand.
The Jupyter Notebook has an option to export the notebook to many formats. It can be accessed by clicking File -> Download as -> PDF via LaTeX (or PDF via HTML - not visible in the screenshot).
Open the notebook you want to download. Click File. Click Download As. Choose a file format, then download your notebook.
All you need to do, is select all the lines you want to comment and press Ctrl + / as shown in below video.
This method is as simple as clicking File, Download as, HTML (. html). Jupyter will then download the notebook as an HTML file to wherever the browser defaults for downloaded files.
You can use this command:
jupyter nbconvert --to python "path/to/notebook.ipynb" \
--TemplateExporter.exclude_markdown=True \
--TemplateExporter.exclude_output_prompt=True \
--TemplateExporter.exclude_input_prompt=True
It will produce a Python file containing only your Python code and without #In[], #Out[]
The \
in the command is just to write the command on multiple lines and can be removed.
To make this configuration permanent:
Create a file named jupyter_nbconvert_config.py
inside the directory ~/.jupyter/
. Create the directory if not existing.
Write inside the file:
from nbconvert import TemplateExporter
TemplateExporter.exclude_markdown=True
TemplateExporter.exclude_output_prompt=True
TemplateExporter.exclude_input_prompt=True
Now you can run the command:
jupyter nbconvert --to python "path/to/notebook.ipynb"
to get a Python file with code only.
Sources: 1 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With