How to effortlessly export Jupyter Notebook's current/visible session into python source code

Context: I was implementing fairly short program to solve algorithmic problems on hackerank on jupyter notebook. After finishing my program, I would need to select only the currently visible source from the jupyter session to submit. The invisible code are erroneous code which has been replaced, so I don't want them. my sample jupyter session

As far as I know, the export function of jupyter will copy not only source but also line numbers, and so on. The %history and %save doesn't provide the function I need also.

Thanks for any help!

Upvotes: 0

Views: 455

Answers (1)

Louise Davies
Louise Davies

Reputation: 15941

I don't know what you mean by invisible code (how is it invisible?) but you might want to take a look at the nbconvert docs, specifically this part about custom templates.

If you want to remove markdown cells and remove prompt numbers (i.e. just have the source code), this is the template you want (saved as mytemplate.tpl in my example but feel free to name it anything with a .tpl):

{% extends 'python.tpl'%}

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

## remove prompt
{% block in_prompt %}
{% endblock in_prompt %}

You can then convert using this tempalte with the command

jupyter nbconvert --to python 'example.ipynb' --template=mytemplate.tpl

Upvotes: 1

Related Questions