简体   繁体   中英

ignore markdown cells in `jupyter nbconvert` with `--to script`

Is it possible to have jupyter nbconvert ... --to script ignore markdown cells rather than convert them to comments?

I'm asking because I want to use flake8 to check the Python code that's generated but I don't want to include the markdown cells (for example, because they are often long lines, and I don't want flake8 to complain about them).

There is the command line argument PythonExporter.exclude_markdown that does what you want. To get a list of pep8 errors that just look at the code cells, I run

jupyter nbconvert my_notebook.ipynb --stdout --to python --PythonExporter.exclude_markdown=True | flake8 - --ignore=W391

This seems to work:

Create a template strip_markdown.tpl

## remove markdown cells
{% extends 'python.tpl'%}
{% block markdowncell -%}
{% endblock markdowncell %}

jupyter nbconvert my_notebook.ipynb --to python --template=strip_markdown.tpl

In case someone else wants to check their jupyter notebooks with CI and the nbconvert + pipe approach doesn't work well enough for you (as it did for me), I want to promote the tool/hack I wrote for this purpose. flake8-nb

I'm asking because I want to use flake8 to check the Python code that's generated

You can do this directly with nbqa :

$ nbqa flake8 my_notebook.ipynb --extend-ignore=E203,E302,E305,E703
my_notebook.ipynb:cell_3:1:1: F401 'import pandas as pd' imported but unused

It also works as a pre-commit hook, see https://nbqa.readthedocs.io/en/latest/pre-commit.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM