Get libraries
Tags: #naas #jupyter-notebooks #read #libraries #snippet
Author: Florent Ravenel

Input

Import libraries

1
import json
2
from pprint import pprint
Copied!

Variables

1
# Input
2
notebook_path = "../template.ipynb"
Copied!

Model

Get module libraries in notebook

1
def get_libraries(notebook_path):
2
with open(notebook_path) as f:
3
nb = json.load(f)
4
data = []
5
6
cells = nb.get("cells")
7
# Check each cells
8
for cell in cells:
9
cell_type = cell.get('cell_type')
10
sources = cell.get('source')
11
for source in sources:
12
if cell_type == "code":
13
if "from" in source and "import" in source:
14
lib = source.replace("\n", "").split("from")[-1].split("import")[0].strip()
15
module = source.replace("\n", "").split("import")[-1].split(" as ")[0].strip()
16
data.append(f"{lib}.{module}")
17
if "from" not in source and "import" in source:
18
library = source.replace("\n", "").split("import")[-1].split(" as ")[0].strip()
19
data.append(library)
20
if len(data) == 0:
21
print("❎ No library found in notebook:", notebook_path)
22
else:
23
print(f"✅ {len(data)} librarie(s) found in notebook:", notebook_path)
24
return data
Copied!

Output

Display result

1
libraries = get_libraries(notebook_path)
2
print(libraries)
Copied!
1
Copied!
Copy link
Edit on GitHub