Links

Get libraries

Tags: #jupyternotebooks #naas #jupyter-notebooks #read #libraries #snippet #operations #text
Author: Florent Ravenel

Input

Import libraries

import json
from pprint import pprint

Variables

# Input
notebook_path = "../template.ipynb"

Model

Get module libraries in notebook

def get_libraries(notebook_path):
with open(notebook_path) as f:
nb = json.load(f)
data = []
cells = nb.get("cells")
# Check each cells
for cell in cells:
cell_type = cell.get('cell_type')
sources = cell.get('source')
for source in sources:
if cell_type == "code":
if "from" in source and "import" in source:
lib = source.replace("\n", "").split("from")[-1].split("import")[0].strip()
module = source.replace("\n", "").split("import")[-1].split(" as ")[0].strip()
data.append(f"{lib}.{module}")
if "from" not in source and "import" in source:
library = source.replace("\n", "").split("import")[-1].split(" as ")[0].strip()
data.append(library)
if len(data) == 0:
print("❎ No library found in notebook:", notebook_path)
else:
print(f"✅ {len(data)} librarie(s) found in notebook:", notebook_path)
return data

Output

Display result

libraries = get_libraries(notebook_path)
print(libraries)