Robert Tucci
Robert Tucci

Reputation: 11

How to execute cell 1 from another notebook in current notebook

I have a bunch of notebooks in a directory dir1 and would like to write a master notebook that executes the first cell of each notebook in dir1. All notebooks in dir1 have markdown describing themselves in cell 1. So by executing the first cell of all of them, the master notebook will document all notebooks in dir1. This sounds easily doable but I don't have any idea how to proceed.

A more general question is, is there software that will extract the markdown in cell 1 of all notebooks in dir1 and create a nice master notebook from them? nbsphinx produces an html doc, but I would like something much more lightweight and quicker.

Upvotes: 0

Views: 386

Answers (1)

Robert Tucci
Robert Tucci

Reputation: 11

Here is the code that I used. I create a notebook called SUMMARY.ipynb inside dir1 and I put this code into a cell of SUMMARY.ipynb. Running this cell produces a nice summary of all the notebooks in dir1 with a link to them

import os
import json
from IPython.display import display, Markdown

# the name of this file
this_fname = 'SUMMARY.ipynb'
fname_to_md = {}
for fname in os.listdir('./'):
    if fname[-6:] == '.ipynb'  and fname != this_fname:
        # print('------------', fname)
        with open(fname, 'r', encoding="utf-8") as f:
            fdata = json.load(f)
            fname_to_md[fname] = ''.join(fdata['cells'][0]['source'])
            # print(fname_to_md)
pre_sep = '\n\n<span style="color:red">%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%</span>\n\n'
full_md = ''
for fname, md in fname_to_md.items():
    sep = pre_sep
    sep += '[<a href="' + fname + '" target= "_blank">' + fname + '</a>]\n\n'
    full_md += sep + md
display(Markdown(full_md))

Upvotes: 1

Related Questions