How to use the nbconvert.writers.FilesWriter function in nbconvert

To help you get started, we’ve selected a few nbconvert examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github takluyver / bookbook / bookbook / latex.py View on Github external
def export(combined_nb: NotebookNode, output_file: Path, pdf=False,
           template_file=None):
    resources = {}
    resources['unique_key'] = 'combined'
    resources['output_files_dir'] = 'combined_files'

    log.info('Converting to %s', 'pdf' if pdf else 'latex')
    exporter = MyLatexPDFExporter() if pdf else MyLatexExporter()
    if template_file is not None:
        exporter.template_file = str(template_file)
    writer = FilesWriter(build_directory=str(output_file.parent))
    output, resources = exporter.from_notebook_node(combined_nb, resources)
    writer.write(output, resources, notebook_name=output_file.stem)
github takluyver / bookbook / bookbook / html.py View on Github external
def convert(source_path: Path, output_dir: Path):
    exporter = MyHTMLExporter()
    writer = FilesWriter(build_directory=str(output_dir))
    output, resources = exporter.from_filename(str(source_path))
    notebook_name = source_path.stem
    writer.write(output, resources, notebook_name=notebook_name)
github jupyter / nbgrader / nbgrader / converters / base.py View on Github external
from ..utils import find_all_files, rmtree, remove
from ..preprocessors.execute import UnresponsiveKernelError
from ..nbgraderformat import SchemaTooOldError, SchemaTooNewError
import typing
from nbconvert.exporters.exporter import ResourcesDict


class NbGraderException(Exception):
    pass


class BaseConverter(LoggingConfigurable):

    notebooks = List([])
    assignments = Dict({})
    writer = Instance(FilesWriter)
    exporter = Instance(Exporter)
    exporter_class = Type(NotebookExporter, klass=Exporter)
    preprocessors = List([])

    force = Bool(False, help="Whether to overwrite existing assignments/submissions").tag(config=True)

    permissions = Integer(
        help=dedent(
            """
            Permissions to set on files output by nbgrader. The default is
            generally read-only (444), with the exception of nbgrader
            generate_assignment and nbgrader generate_feedback, in which case
            the user also has write permission.
            """
        )
    ).tag(config=True)
github Metatab / metatab / metapack / package / filesystem.py View on Github external
from metapack.jupyter.exporters import DocumentationExporter

        notebook_docs = []

        # First find and remove them from the doc.
        for term in list(self.doc['Documentation'].find('Root.Documentation')):
            u = parse_app_url(term.value)
            if u.target_format == 'ipynb':
                notebook_docs.append(term)
                self.doc.remove_term(term)

        # Process all of the normal files
        super()._load_documentation_files()

        de = DocumentationExporter()
        fw = FilesWriter()
        fw.build_directory = join(self.package_path.path,'docs')

        # Now, generate the documents directly into the filesystem package
        for term in notebook_docs:
            u = parse_app_url(term.value)
            nb_path = u.path(self.source_dir)

            output, resources = de.from_filename(nb_path)
            fw.write(output, resources, notebook_name='notebook')

            de.update_metatab(self.doc, resources)
github has2k1 / plotnine / doc / sphinxext / include_example.py View on Github external
# Read notebook
    with open(notebook_filename, 'r') as f:
        nb = nbformat.read(f, as_version=4)

    # Export
    rst_exporter = nbsphinx.Exporter(execute='never', allow_errors=True)
    (body, resources) = rst_exporter.from_notebook_node(
        nb, resources_d)

    # Correct path for the resources
    for filename in list(resources['outputs'].keys()):
        tmp = '{}/{}'.format(path, filename)
        resources['outputs'][tmp] = resources['outputs'].pop(filename)

    fw = FilesWriter()
    fw.build_directory = path
    # Prevent "not in doctree" complains
    resources['output_extension'] = '.txt'
    body = 'Examples\n--------\n' + body
    return fw.write(body, resources, notebook_name=basename)
github jupyter / nbgrader / nbgrader / converters / base.py View on Github external
def start(self) -> None:
        self.init_notebooks()
        self.writer = FilesWriter(parent=self, config=self.config)
        self.exporter = self.exporter_class(parent=self, config=self.config)
        for pp in self.preprocessors:
            self.exporter.register_preprocessor(pp)
        currdir = os.getcwd()
        os.chdir(self.coursedir.root)
        try:
            self.convert_notebooks()
        finally:
            os.chdir(currdir)
github Metatab / metatab / metatab / jupyter / convert.py View on Github external
nb_path = Url(m.mt_file).parts.path

    c = Config()

    pe = PackageExporter(config=c, log=logger)

    prt('Running the notebook')

    pe.run(nb_path)

    de = DocumentationExporter(config=c, log=logger, metadata=doc_metadata(pe.doc))

    prt('Exporting documentation')
    output, resources = de.from_filename(nb_path)

    fw = FilesWriter()
    fw.build_directory = join(pe.output_dir,'docs')
    fw.write(output, resources, notebook_name='notebook')

    new_mt_file = join(pe.output_dir, DEFAULT_METATAB_FILE)

    doc = MetatabDoc(new_mt_file)

    de.update_metatab(doc, resources)

    for lib_dir in pe.lib_dirs:

        lib_dir = normpath(lib_dir).lstrip('./')

        doc['Resources'].new_term("Root.PythonLib", lib_dir)

        path = abspath(lib_dir)
github jupyter / jupyter-sphinx / jupyter_sphinx / execute.py View on Github external
def write_notebook_output(notebook, output_dir, notebook_name, location=None):
    """Extract output from notebook cells and write to files in output_dir.

    This also modifies 'notebook' in-place, adding metadata to each cell that
    maps output mime-types to the filenames the output was saved under.
    """
    resources = dict(unique_key=os.path.join(output_dir, notebook_name), outputs={})

    # Modifies 'resources' in-place
    ExtractOutputPreprocessor().preprocess(notebook, resources)
    # Write the cell outputs to files where we can (images and PDFs),
    # as well as the notebook file.
    FilesWriter(build_directory=output_dir).write(
        nbformat.writes(notebook),
        resources,
        os.path.join(output_dir, notebook_name + ".ipynb"),
    )
    # Write a script too.  Note that utf-8 is the de facto
    # standard encoding for notebooks. 
    ext = notebook.metadata.get("language_info", {}).get("file_extension", None)
    if ext is None:
        ext = ".txt"
        js.logger.warning(
            "Notebook code has no file extension metadata, " "defaulting to `.txt`",
            location=location,
        )
    contents = "\n\n".join(cell.source for cell in notebook.cells)
    with open(os.path.join(output_dir, notebook_name + ext), "w",
              encoding = "utf8") as f: