简体   繁体   中英

load code from a code cell from one jupyter notebook into another jupyter notebook

I want to load (ie, copy the code as with %load) the code from a code cell in one jupyter notebook into another jupyter notebook (Jupyter running Python, but not sure if that matters). I would really like to enter something like

%load cell[5] notebookname.ipynb

The command copies all code in cell 5 of notebookname.ipynb to the code cell of the notebook I am working on. Does anybody know a trick how to do that?

Adapting some code found here at Jupyter Notebook, the following will display the code of a specific cell in the specified notebook:

import io
from nbformat import read

def print_cell_code(fname, cellno):
    with io.open(fname, 'r', encoding='utf-8') as f:
        nb = read(f, 4)
    cell = nb.cells[cellno]
    print(cell.source)

print_cell_code("Untitled.ipynb",2)

Not sure what you want to do once the code is there, but maybe this can be adapted to suit your needs. Try print(nb.cells) to see what read brings in.

You'll probably want to use or write your own nbconvert preprocessor to extract a cell from one and insert into another. There is a good amount research into these docs it takes to understand how to write your preprocessor, but this is the preferred way.

The quick fix option you have is that the nbformat specification is predicated on JSON, which means that if you read in a ipynb file with pure python (ie with open and read ), you can call json.loads on it to turn the entire file into a dict . From there, you can access cells in the cells entry (which is a list of cells). So, something like like this:

import json

with open("nb1.ipynb", "r") as nb1, open("nb2.ipynb", "r") as nb2:
    nb1, nb2 = json.loads(nb1.read()), json.loads(nb2.read())
    nb2["cells"].append(nb1["cells"][0]) # adds nb1's first cell to end of nb2

This assumes (as does your question) there is no metadata conflict between the notebooks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM