Last active
March 15, 2020 21:10
-
-
Save lebedov/8718735 to your computer and use it in GitHub Desktop.
Consecutively renumber prompts in an IPython notebook.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" | |
Consecutively renumber prompts in an IPython notebook. | |
""" | |
# Copyright (c) 2015, Lev Givon | |
# All rights reserved. | |
# Distributed under the terms of the BSD license: | |
# http://www.opensource.org/licenses/bsd-license | |
import argparse | |
import simplejson | |
def renumber(data): | |
""" | |
Consecutively renumbers prompts in IPython notebook data. | |
""" | |
# Unserialize: | |
d = simplejson.loads(data) | |
if d['nbformat'] < 4: | |
raise RuntimeError('Can only renumber notebooks with format 4 or later') | |
prompt_num = 1 | |
for cell in d['cells']: | |
if cell['cell_type'] == 'code': | |
cell['execution_count'] = prompt_num | |
if cell.has_key('outputs'): | |
for out in cell['outputs']: | |
out['execution_count'] = prompt_num | |
prompt_num += 1 | |
# Reserialize: | |
return simplejson.dumps(d, indent=' ') | |
parser = argparse.ArgumentParser() | |
parser.add_argument('input_file', help='Input file') | |
parser.add_argument('output_file', help='Output file') | |
args = parser.parse_args() | |
with open(args.input_file, 'r') as fi, \ | |
open(args.output_file, 'w') as fo: | |
fo.write(renumber(fi.read())) |
Workaround is to downgrade the notebook version to 3:
ipython nbconvert FOO.ipynb --to notebook --nbformat=3 --output FOO_v3.ipynb
./ipynb_renumber.py FOO_v3.ipynb FOO_v3_renumbered.ipynb
Then opening FOO_v3_renumbered.ipynb will convert back to v4 notebook
Modified to work with v4 notebooks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ ./ipynb_renumber.py OLD.ipynb NEW.ipynb
Traceback (most recent call last):
File "./ipynb_renumber.py", line 39, in
fo.write(renumber(fi.read()))
File "./ipynb_renumber.py", line 17, in renumber
cells = d['worksheets'][0]['cells']
KeyError: 'worksheets'
$ ipython notebook --version
3.1.0