Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically convert jupyter notebook to .py

I know there have been a few questions about this but I have not found anything robust enough.

Currently I am using, from terminal, a command that creates .py, then moves them to another folder:

jupyter nbconvert --to script '/folder/notebooks/notebook.ipynb' &&  \
mv ./folder/notebooks/*.py ./folder/python_scripts && \

The workflow then is to code in a notebook, check with git status what changed since last commit, create a potentially huge number of nbconvert commands, then move them all.

I would like to use something like !jupyter nbconvert --to scriptfound in this answer, but without the cell that crates the python file appearing in the .py itself.

Because if that line appears, my code won't ever work right.

So, is there a proper way of dealing with this problem? One that can be automated, and not manually copying files names, creating the command, executing and then starting again.

like image 609
monkey intern Avatar asked Mar 03 '23 15:03

monkey intern


1 Answers

You can add the following code in the last cell in your notebook file.

!jupyter nbconvert --to script mycode.ipynb
with open('mycode.py', 'r') as f:
    lines = f.readlines()
with open('mycode.py', 'w') as f:
    for line in lines:
        if 'nbconvert --to script' in line:
            break
        else:
            f.write(line)

It will generate the .py file and then remove this very code from it. You will end up with a clean script that will not call !jupyter nbconvert anymore.

like image 120
alec_djinn Avatar answered Mar 10 '23 11:03

alec_djinn