Skip to content

Instantly share code, notes, and snippets.

@apoorvnandan
Last active January 20, 2020 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apoorvnandan/03580725ddb507158859395a97f2c8f0 to your computer and use it in GitHub Desktop.
Save apoorvnandan/03580725ddb507158859395a97f2c8f0 to your computer and use it in GitHub Desktop.
Convert jupyter notebook to python script (inspired by nbdev)
##
# usage:
# 1. Add '#export' as the first line of the cells you want to export.
# This script will ignore all other cells.
# 2. $python convert_nb_script.py -n sample.ipynb > sample_script.py
#
# You can use other tags to selectively export other cells
# eg. Add tag #test to the cells containing unit tests
# python convert_nb_script.py -n sample.ipynb -t test > unit_tests.py
##
import nbformat
from argparse import ArgumentParser
def parse_args():
parser = ArgumentParser()
parser.add_argument('-n', '--notebook', type=str)
parser.add_argument('-t', '--tag', type=str, default='export')
return parser.parse_args()
def print_code(file, export='#export'):
with open(file, encoding='utf-8') as f:
nb = nbformat.reads(f.read(), as_version=4)
cells = nb['cells']
did_i_start = False
for cell in cells:
if cell['cell_type'] == 'code' and cell['source'][:len(export)] == export:
src = cell['source']
if not did_i_start:
did_i_start = True
print(src.replace('#export\n', ''))
else:
print('\n')
print(src.replace('#export\n', ''))
if __name__ == '__main__':
args = parse_args()
print_code(args.notebook, export='#' + args.tag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment