Skip to content

Latest commit

 

History

History
87 lines (65 loc) · 2.87 KB

Jupyter_Notebooks_Get_libraries.md

File metadata and controls

87 lines (65 loc) · 2.87 KB



Template request | Bug report | Generate Data Product

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

Author: Florent Ravenel

Description: This notebook provides instructions on how to install and use libraries in Jupyter Notebooks.

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)