Created
April 14, 2021 18:25
-
-
Save rkern/7bf123b94079821d2764a498de40a580 to your computer and use it in GitHub Desktop.
Page Jupyter notebooks on the terminal
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 | |
# -*- coding: utf-8 -*- | |
""" Page Jupyter notebooks on the terminal. | |
Can be used to search with ripgrep: | |
$ rg --pre nbcat --pre-glob "*.ipynb" <search_term> | |
To the extent possible under law, Robert Kern has waived all copyright | |
and related or neighboring rights to nbcat. | |
This work is published from: United States. | |
CC0: https://creativecommons.org/publicdomain/zero/1.0/ | |
""" | |
from io import BytesIO | |
import nbformat | |
from IPython.core.page import pager_page | |
__version__ = '1.0' | |
NBFORMAT_VERSION = 4 | |
class NotebookTransformer(object): | |
""" Transform IPython notebook files into searchable text. | |
""" | |
def __call__(self, filename, mode='rb'): | |
g = BytesIO() | |
g.write('## {}\n\n'.format(filename).encode('utf-8')) | |
root = nbformat.read(filename, NBFORMAT_VERSION) | |
for cell in root.cells: | |
ec = getattr(cell, 'execution_count', ' ') | |
if not ec: | |
ec = ' ' | |
in_line = u'# In[{}]:\n'.format(ec) | |
g.write(in_line.encode('utf-8')) | |
g.write(cell.source.encode('utf-8')) | |
g.write(b'\n\n') | |
g.seek(0, 0) | |
return g | |
def main(): | |
import argparse | |
parser = argparse.ArgumentParser( | |
formatter_class=argparse.ArgumentDefaultsHelpFormatter) | |
parser.add_argument('nbfiles', metavar='IPYNB', nargs='+', | |
help='IPython notebook files to display.') | |
args = parser.parse_args() | |
xform = NotebookTransformer() | |
for fn in args.nbfiles: | |
data = xform(fn).getvalue() | |
pager_page(data.decode('utf-8')) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment