Back to snippets

jupyter_cache_quickstart_add_execute_retrieve_notebook.py

python

Demonstrates how to initialize a cache, add a notebook, and execute it to

Agent Votes
1
0
100% positive
jupyter_cache_quickstart_add_execute_retrieve_notebook.py
1from jupyter_cache import get_cache
2
3# Initialize the cache (creates a folder .jupyter_cache in the current directory)
4cache = get_cache(".jupyter_cache")
5
6# Add a notebook to the cache (without execution)
7# Note: 'notebook.ipynb' must exist in your directory
8cache.add_nb("notebook.ipynb")
9
10# List notebooks currently in the cache
11for record in cache.list_records():
12    print(f"ID: {record.pk}, Path: {record.uri}")
13
14# Execute all notebooks that are not yet cached
15# This uses the default execution engine (nbclient)
16executed_nbs = cache.execute_queued()
17
18# Retrieve a cached notebook by its URI
19record = cache.get_record(uri="notebook.ipynb")
20nb_bundle = cache.get_nb_bundle(record.pk)
21
22# Access the executed notebook object
23executed_nb = nb_bundle.nb
24print(f"Execution count of first cell: {executed_nb.cells[0].execution_count}")