Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Save cleared notebooks as target version #5

Merged
merged 2 commits into from
Aug 16, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 27 additions & 20 deletions clearoutputs.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
#!/usr/bin/env python
from __future__ import print_function

import sys
import argparse
import io
import os

from nengo.utils.ipython import read_nb, write_nb


Expand Down Expand Up @@ -35,37 +36,43 @@ def remove_outputs(nb):
ws.cells.remove(cell)


def clear_file(fname):
try:
with io.open(fname, 'r') as f:
nb = read_nb(f)
remove_outputs(nb)
with io.open(fname, 'w', encoding='utf8') as f:
write_nb(nb, f)
f.write(u'\n')
print("wrote %s" % fname)
except Exception as e:
print("Skipping '%s' due to %s:\n %s"
% (fname, e.__class__.__name__, e))
def clear_file(fname, target_version):
with io.open(fname, 'r') as f:
nb = read_nb(f)
remove_outputs(nb)
with io.open(fname, 'w', encoding='utf8') as f:
write_nb(nb, f, version=target_version)
f.write(u'\n')
print("wrote %s" % fname)


def clear_files(fnames):
def clear_files(fnames, target_version):
for fname in fnames:
if os.path.isdir(fname):
clear_directory(fname)
clear_directory(fname, target_version=target_version)
else:
clear_file(fname)
clear_file(fname, target_version=target_version)


def clear_directory(dname):
def clear_directory(dname, target_version):
assert os.path.isdir(dname)
fnames = os.listdir(dname)
fpaths = [os.path.join(dname, fname) for fname in fnames
if not fname.startswith('.')]
clear_files([fpath for fpath in fpaths
if os.path.isdir(fpath) or fpath.endswith('.ipynb')])
if os.path.isdir(fpath) or fpath.endswith('.ipynb')],
target_version=target_version)


if __name__ == '__main__':
fnames = sys.argv[1:]
clear_files(fnames)
parser = argparse.ArgumentParser(
description="Clear all outputs in Jupyter notebooks.")
parser.add_argument(
'--target-version', type=int, default=3,
help="Version of notebook format to save.")
parser.add_argument(
'fnames', nargs='+',
help="Files to process. Will recursively descend into directories")
args = parser.parse_args()

clear_files(args.fnames, target_version=args.target_version)