Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ipython Notebook writefile and execute cell at the same time

When using the magic cell %%writefile, it seems that ipython treat the content of the cell as plain txt and will not execute it.

Is there any way to run the code in the cell and then automatically export it to some script file?

This is useful because it gives you the ability to programmatically sync your notebook with a script that only keep some parts of the notebook.

In the notebook, some codes are only scaffolds, downloading the notebook as a py script will include these unnecessary codes. Meanwhile, you may want to re-structure the document, put two code blocks together while in the notebook there are a lot of draft content between them.

Ugly, all of the above things can be done by copying codes manually. But it will make future maintenance full of tedious recopy and paste work.

like image 741
empenguin Avatar asked Oct 27 '15 01:10

empenguin


1 Answers

Thanks to author for answer. I think full code will be useful for others:

from IPython.core.magic import register_cell_magic


@register_cell_magic
def write_and_run(line, cell):
    argz = line.split()
    file = argz[-1]
    mode = 'w'
    if len(argz) == 2 and argz[0] == '-a':
        mode = 'a'
    with open(file, mode) as f:
        f.write(cell)
    get_ipython().run_cell(cell)

You can declare this in your Jupiter notebook. Mark cells like:

%%write_and_run some.py 

or

%%write_and_run -a some.py 
like image 129
Andrei Iatsuk Avatar answered Sep 22 '22 06:09

Andrei Iatsuk