In [1]:
import sys
import os, os.path
from IPython import get_ipython
import nbformat
import io
import time

NBVERSION = 4

In [3]:
def compile_to_py(nb_path,py_path):

    shell = get_ipython()

    # load the notebook object
    with io.open(nb_path, 'r', encoding='utf-8') as f:
        nb = nbformat.read(f,NBVERSION)

    with io.open(py_path,'w',encoding='utf-8') as pyf:
        pyf.write(u'## Compiled from {} on {}\n'.format(nb_path,time.ctime()))
        for cell in nb['cells']:
            if cell['cell_type'] == 'code':
                # transform the input to executable Python
                ##print ("Source",cell['source'])
                ec = cell['execution_count']
                code = shell.input_transformer_manager.transform_cell(cell['source'])
                if code.startswith('##test:'):
                    continue
                if code.startswith('get_ipython().run_cell_magic('):
                    continue
                if code.startswith('## Test Section:'):
                    pyf.write(u'\n## Import ended by "## Test Section:"\n')
                    break
                if code.startswith('#### End Import ####'):
                    pyf.write(u'\n## Import ended by "#### End Import ####"\n')
                    break

                pyf.write(u'\n')
                pyf.write(u'## In [{}]:\n'.format(' ' if ec is None else ec))
                pyf.write(code)

In [10]:
def must_compile(nb_path,py_path):
    if nb_path.startswith('00'):
        return False
    if nb_path.startswith('05'):
        return False
    if not os.path.exists(py_path):
        return True
    nbt = os.path.getmtime(nb_path)
    pyt = os.path.getmtime(py_path)
    return pyt < nbt

In [14]:
flist = !ls *.ipynb
for inf in flist:
    outf = inf[:-6] + '.py'
    if must_compile(inf,outf):
        print('Compiling {} => {}'.format(inf,outf))
        compile_to_py(inf,outf)


Compiling Frame2D_Base.ipynb => Frame2D_Base.py
Compiling Frame2D_Display.ipynb => Frame2D_Display.py
Compiling Frame2D_Input.ipynb => Frame2D_Input.py
Compiling Frame2D_Output.ipynb => Frame2D_Output.py
Compiling Frame2D_SolveFirstOrder.ipynb => Frame2D_SolveFirstOrder.py
Compiling LoadSets.ipynb => LoadSets.py
Compiling MemberLoads.ipynb => MemberLoads.py
Compiling Members.ipynb => Members.py
Compiling NodeLoads.ipynb => NodeLoads.py
Compiling Nodes.ipynb => Nodes.py
Compiling Tables.ipynb => Tables.py

In [12]:
!ls *.py


Frame2D_Base.py     Frame2D_SolveFirstOrder.py	MemberLoads.py	Tables.py
Frame2D_Display.py  __init__.py			Members.py	test.py
Frame2D_Input.py    ipynb_compiler.py		NodeLoads.py
Frame2D_Output.py   LoadSets.py			Nodes.py

In [13]:
!touch *.ipynb

In [ ]: