Skip to content

Instantly share code, notes, and snippets.

@vincentqb
Last active April 12, 2022 23:37
Show Gist options
  • Select an option

  • Save vincentqb/91a0d79a8d2c7c4666c56e8e0db3be29 to your computer and use it in GitHub Desktop.

Select an option

Save vincentqb/91a0d79a8d2c7c4666c56e8e0db3be29 to your computer and use it in GitHub Desktop.
Comment out line and cell magic from jupyter notebook, see https://github.com/ipython/ipython/issues/3707#issuecomment-1097362068

Leaving a note here to adjust the solution above for cell magic (e.g. %%time), with nbconvert > 6.0.

In nbconvert_config.py:

def comment_magics(input, **kwargs):
    if input.startswith("%"):
        input = "# " + input
    return input


# Export all the notebooks in the current directory to the sphinx_howto format
c = get_config()
c.NbConvertApp.notebooks = ["*.ipynb"]
c.Exporter.filters = {"comment_magics": comment_magics}

In python_nomagic/index.py.j2:

{%- extends 'null.j2' -%}

## set to python3
{%- block header -%}
#!/usr/bin/env python3
# coding: utf-8
{% endblock header %}

## remove cell counts entirely
{% block in_prompt %}
{% if resources.global_content_filter.include_input_prompt -%}
{% endif %}
{% endblock in_prompt %}

## remove markdown cells entirely
{% block markdowncell %}
{% endblock markdowncell %}

{% block input %}
{{ cell.source | comment_magics | ipython2python }}    
{% endblock input %}

In python_nomagic/conf.json:

{
    "base_template": "base",
    "mimetypes": {
        "text/x-python": true
    }
}

Convert with:

jupyter nbconvert --config ./nbconvert_config.py --to python --template ./python_nomagic notebook.ipynb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment