Example #1
0
def execute_and_clear(notebook_file_name, source_dir):
    nb = nbformat.read(notebook_file_name, nbformat.NO_CONVERT)
    replacements = []
    for cell in nb["cells"]:
        if isinstance(cell, MutableMapping):
            if cell["cell_type"] == "code" and "# Setup" not in cell["source"]:
                continue
            if "metadata" in cell and "pycharm" in cell["metadata"]:
                del cell["metadata"]["pycharm"]
            replacements.append(cell)
    nb["cells"] = replacements
    executed = pre.execute.executenb(nb, cwd=source_dir)
    cop = pre.ClearOutputPreprocessor()
    nb, _ = cop.preprocess(executed, {})
    return nb
Example #2
0
def execute_and_clear(notebook_file_name, source_dir):
    nb = nbformat.read(notebook_file_name, nbformat.NO_CONVERT)
    replacements = []
    for cell in nb["cells"]:
        code_cell = cell.get("cell_type", None) == "code"
        source = cell.get("source", "")
        if code_cell and ("# Setup" not in source
                          or "### Explanation" in source):
            continue
        if "metadata" in cell and "pycharm" in cell["metadata"]:
            del cell["metadata"]["pycharm"]
        replacements.append(cell)
    nb["cells"] = replacements
    executed = pre.execute.executenb(nb, cwd=source_dir)
    cop = pre.ClearOutputPreprocessor()
    nb, _ = cop.preprocess(executed, {})
    return nb
Example #3
0
    spyder_dir = os.path.join("..", "course", term, "spyder")
    ep = ExecutePreprocessor(timeout=600, kernel_name="python3")
    nb_hash = "" if nb_file not in hashes else hashes[nb_file]

    cell_source = ""
    for cell in nb["cells"]:
        source = "" if "source" not in cell else cell["source"]
        cell_source += source.strip()
    current = sha512(cell_source.encode("utf-8")).hexdigest()
    nb_changed = current != nb_hash
    if nb_changed:
        ep.preprocess(nb, {"metadata": {"path": source_dir}})
        print(f"Writing executed version of {nb_file}")
        nbformat.write(nb, nb_file, nbformat.NO_CONVERT)
        hashes[nb_file] = current
    cop = pre.ClearOutputPreprocessor()
    nb, _ = cop.preprocess(nb, {})
    retain = []
    for cell in nb["cells"]:
        cell_type = cell.get("cell_type", None)
        source = cell.get("source", "")
        if cell_type == "markdown" and "#### Explanation" in source:
            continue
        if cell_type == "code" and "# Setup" not in cell["source"]:
            cell["source"] = ""
        if "metadata" in cell and "pycharm" in cell["metadata"]:
            del cell["metadata"]["pycharm"]
        retain.append(cell)
    # Filter repeated empty cells
    keep = []
    for i, cell in enumerate(reversed(retain)):