Exemplo n.º 1
0
def _replace_temp_python_file_references_in_out_err(
    temp_python_file: str,
    notebook: str,
    out: str,
    err: str,
) -> Output:
    """
    Replace references to temporary Python file with references to notebook.

    Parameters
    ----------
    temp_python_file
        Temporary Python file where notebook was converted to.
    notebook
        Original Jupyter notebook.
    out
        Captured stdout from third-party tool.
    err
        Captured stderr from third-party tool.

    Returns
    -------
    Output
        Stdout, stderr with temporary directory replaced by current working directory.
    """
    py_basename = os.path.basename(temp_python_file)
    nb_basename = os.path.basename(notebook)
    out = out.replace(py_basename, nb_basename)
    err = err.replace(py_basename, nb_basename)

    out = out.replace(
        remove_suffix(py_basename, ".py"), remove_suffix(nb_basename, ".ipynb")
    )
    err = err.replace(
        remove_suffix(py_basename, ".py"), remove_suffix(nb_basename, ".ipynb")
    )

    return Output(out, err)
Exemplo n.º 2
0
def _get_nb_to_py_mapping(
    root_dirs: Sequence[str], files: Optional[str], exclude: Optional[str]
) -> Dict[str, TemporaryFile]:
    """
    Get mapping between notebooks and temporary Python files.

    Parameters
    ----------
    root_dirs
        All the notebooks/directories passed in via the command-line.
    files
        Pattern of files to include.
    exclude
        Pattern of files to exclude.

    Returns
    -------
    Dict[str, Tuple[int, str]]
        Mapping between notebooks and temporary Python files.

    Raises
    ------
    FileNotFoundError
        If notebook isn't found.
    """
    nb_to_py_mapping: Dict[str, TemporaryFile] = {}
    for notebook in _get_all_notebooks(root_dirs, files, exclude):
        if not os.path.exists(notebook):
            _clean_up_tmp_files(nb_to_py_mapping)
            raise FileNotFoundError(
                f"{BOLD}No such file or directory: {notebook}{RESET}\n"
            )

        nb_to_py_mapping[notebook] = TemporaryFile(
            *tempfile.mkstemp(
                dir=os.path.dirname(notebook),
                prefix=remove_suffix(os.path.basename(notebook), ".ipynb"),
                suffix=".py",
            )
        )
        relative_path, _ = get_relative_and_absolute_paths(
            nb_to_py_mapping[notebook].file
        )
        nb_to_py_mapping[notebook] = nb_to_py_mapping[notebook]._replace(
            file=relative_path
        )
    return nb_to_py_mapping