Skip to content

Instantly share code, notes, and snippets.

@zehanort
Last active July 19, 2020 19:21
Show Gist options
  • Save zehanort/f53a6621a979d4888f2a1be5165542f7 to your computer and use it in GitHub Desktop.
Save zehanort/f53a6621a979d4888f2a1be5165542f7 to your computer and use it in GitHub Desktop.
Ever wanted to reset the execution counts of the cells of a jupyter notebook to make it more presentable (or to hide experiments and tweaks from your teachers or colleagues) but re-running everything was not an option (too long, too risky, the numbers happened to be toooooo good)? Well, now you have a way!
import argparse
import json
parser = argparse.ArgumentParser(
description='Reset the execution count of the code cells of a jupyter notebook'
)
parser.add_argument('notebook', help='the input jupyter notebook')
parser.add_argument('-i', '--inplace',
help='change the notebook file inplace', action='store_true')
parser.add_argument('-o', '--output',
help='if not inplace, the name of the output notebook')
args = parser.parse_args()
with open(args.notebook, 'r') as f:
notebook_json = json.load(f)
exec_cnt = 1
for cell in filter(lambda c : c['cell_type'] == 'code', notebook_json['cells']):
cell['execution_count'] = exec_cnt
if 'outputs' in cell:
for o in cell['outputs']:
if 'execution_count' in o:
o['execution_count'] = exec_cnt
exec_cnt += 1
if args.inplace:
print('WARNING: You are about to overwrite the `%s` jupyter notebook file!' % args.notebook)
if input('Are you sure you want to continue? [y/N] ') != 'y':
print('Aborted.')
exit(0)
outfile = args.notebook
else:
if args.output is not None:
outfile = args.output
else:
outfile = args.notebook.split('.ipynb')[0] + '_reset.ipynb'
with open(outfile, 'w') as f:
json.dump(notebook_json, f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment