当前位置: 首页>>代码示例>>Python>>正文


Python nbconvert.HTMLExporter方法代码示例

本文整理汇总了Python中nbconvert.HTMLExporter方法的典型用法代码示例。如果您正苦于以下问题:Python nbconvert.HTMLExporter方法的具体用法?Python nbconvert.HTMLExporter怎么用?Python nbconvert.HTMLExporter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在nbconvert的用法示例。


在下文中一共展示了nbconvert.HTMLExporter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: export_html

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def export_html(nb, f):
  config = {
      'Exporter': {
          'template_file': 'basic',
          'template_path': ['./sphinxext/']
      },
      'ExtractOutputPreprocessor': {
          'enabled': True
      },
      'CSSHTMLHeaderPreprocessor': {
          'enabled': True
      }
  }

  exporter = HTMLExporter(config)
  body, resources = exporter.from_notebook_node(
      nb, resources={'output_files_dir': f['nbname']})

  for fn, data in resources['outputs'].items():
    bfn = os.path.basename(fn)
    with open("{destdir}/{fn}".format(fn=bfn, **f), 'wb') as res_f:
      res_f.write(data)

  return body 
开发者ID:deepchem,项目名称:deepchem,代码行数:26,代码来源:notebook_sphinxext.py

示例2: export_html

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def export_html(nb, f):
    config = {
        'Exporter': {'template_file': 'embed',
                     'template_path': ['./sphinxext/']},
        'ExtractOutputPreprocessor': {'enabled': True},
        'CSSHTMLHeaderPreprocessor': {'enabled': True}
    }

    exporter = HTMLExporter(config)
    body, resources = exporter.from_notebook_node(
        nb, resources={'output_files_dir': f['nbname']})

    for fn, data in resources['outputs'].items():
        bfn = os.path.basename(fn)
        with open("{destdir}/{fn}".format(fn=bfn, **f), 'wb') as res_f:
            res_f.write(data)

    return body 
开发者ID:msmbuilder,项目名称:mdentropy,代码行数:20,代码来源:notebook_sphinxext.py

示例3: notebook_view

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def notebook_view(request_args):
    check.dict_param(request_args, 'request_args')

    # This currently provides open access to your file system - the very least we can
    # do is limit it to notebook files until we create a more permanent solution.
    path = request_args['path']
    if not path.endswith('.ipynb'):
        return 'Invalid Path', 400

    with open(os.path.abspath(path)) as f:
        read_data = f.read()
        notebook = nbformat.reads(read_data, as_version=4)
        html_exporter = HTMLExporter()
        html_exporter.template_file = 'basic'
        (body, resources) = html_exporter.from_notebook_node(notebook)
        return '<style>' + resources['inlining']['css'][0] + '</style>' + body, 200 
开发者ID:dagster-io,项目名称:dagster,代码行数:18,代码来源:app.py

示例4: generate_html_from_notebook

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def generate_html_from_notebook(self, nb: NotebookNode) -> Text:
        """Converts a provided NotebookNode to HTML.

        Args:
            nb: NotebookNode that should be converted to HTML.

        Returns:
            HTML from converted NotebookNode as a string.

        """
        # HTML generator and exporter object
        html_exporter = HTMLExporter()
        template_file = "templates/{}.tpl".format(self.template_type.value)
        html_exporter.template_file = str(Path.cwd() / template_file)
        # Output generator
        self.ep.preprocess(nb, {"metadata": {"path": Path.cwd()}}, self.km)
        # Export all html and outputs
        body, _ = html_exporter.from_notebook_node(nb, resources={})
        return body 
开发者ID:kubeflow,项目名称:pipelines,代码行数:21,代码来源:exporter.py

示例5: __init__

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def __init__(self, builderSelf):
        
        self.htmldir = builderSelf.outdir + "/html" #html directory 

        for path in [self.htmldir]:
            ensuredir(path)
        self.html_exporter = HTMLExporter()
        
        templateFolder = builderSelf.config['jupyter_template_path']

        if os.path.exists(templateFolder):
            pass
        else:
            builderSelf.logger.warning("template directory not found")
            exit()

        self.html_exporter.template_file = templateFolder + "/" + builderSelf.config["jupyter_html_template"] 
开发者ID:QuantEcon,项目名称:sphinxcontrib-jupyter,代码行数:19,代码来源:convert.py

示例6: export_html

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def export_html(self, pathname):
        """
        Export notebook to .html file
        :param pathname: output filename
        :return:
        """

        html_exporter = HTMLExporter()

        (body, resources) = html_exporter.from_notebook_node(self.nb)

        if pathname == '-':
            sys.__stdout__.write(body)
        else:
            with open(pathname, 'w') as f:
                f.write(body)

        logging.info("HTML notebook exported to '{}'".format(pathname)) 
开发者ID:elehcimd,项目名称:pynb,代码行数:20,代码来源:notebook.py

示例7: export_notebook

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def export_notebook(nb, cid):
    nb = nbformat.from_dict(nb)
    html_exporter = HTMLExporter()
    html_exporter.template_file = "basic"
    body = html_exporter.from_notebook_node(nb)[0]
    soup = BeautifulSoup(body, "html.parser")
    # mark cells with special name for toggling, and
    # TODO make element id's unique by appending cid (for ingester)
    for div in soup.find_all("div", "output_wrapper"):
        script = div.find("script")
        if script:
            script = script.contents[0]
            if script.startswith("render_json"):
                div["name"] = "HData"
            elif script.startswith("render_table"):
                div["name"] = "Tables"
            elif script.startswith("render_plot"):
                div["name"] = "Graphs"
        else:
            pre = div.find("pre")
            if pre and pre.contents[0].startswith("Structure"):
                div["name"] = "Structures"
    # name divs for toggling code_cells
    for div in soup.find_all("div", "input"):
        div["name"] = "Code"
    # separate script
    script = []
    for s in soup.find_all("script"):
        script.append(s.string)
        s.extract()  # remove javascript
    return soup.prettify(), "\n".join(script) 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:33,代码来源:views.py

示例8: convert

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def convert():
    exporter = HTMLExporter()
    exporter.template_path = [os.path.join('docs', 'templates')]
    exporter.template_file = 'full'
    for source_ipynb_path in gen_notebook_path():
        arrange_notebook_execution_order(source_ipynb_path)
        _, filename = os.path.split(source_ipynb_path)

        body, _ = exporter.from_filename(source_ipynb_path)
        write_path = os.path.join('docs', filename.replace('ipynb', 'html'))
        with open(write_path, 'wt', encoding='utf-8') as f:
            f.write(body)
        print('{} write success.'.format(write_path)) 
开发者ID:Sorosliu1029,项目名称:Jike-Metro,代码行数:15,代码来源:convert.py

示例9: notebook_to_html

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def notebook_to_html(content, htmlfile):
    """ Convert notebook to html file.

    Parameters
    ----------

    content : nbformat.NotebookNode
        A dict-like node of the notebook with attribute-access
    htmlfile : str
        Filename for the notebook exported as html
    """
    # prepare html exporter, anchor_link_text=' ' suppress anchors being shown
    html_exporter = HTMLExporter(
        anchor_link_text=' ', exclude_input_prompt=True, exclude_output_prompt=True
    )

    # save metadata for possible title removement
    metadata = content['metadata']

    # export to html
    content, _ = html_exporter.from_notebook_node(content)

    # check if export path exists
    if os.path.dirname(htmlfile) != '' and not os.path.isdir(os.path.dirname(htmlfile)):
        raise FileNotFoundError(f'Path to html-file does not exist: {os.path.dirname(htmlfile)}')

    # Remove title from htmlfile if none is set to prevent pandoc from writing one
    if 'title' not in metadata:
        content = remove_html_title(content)

    # write content to html file
    with open(htmlfile, 'w', encoding='utf-8') as file:
        file.write(content) 
开发者ID:m-rossi,项目名称:jupyter-docx-bundler,代码行数:35,代码来源:converters.py

示例10: _generate_html

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def _generate_html(self, node, substitutions):  # pragma: no cover
        exporter = HTMLExporter()
        exporter.register_preprocessor(Substitute(self.nbversion,
                                                  substitutions))
        html,_ = exporter.from_notebook_node(node)
        return html 
开发者ID:holoviz,项目名称:holoviews,代码行数:8,代码来源:archive.py

示例11: _write_output_to_s3

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def _write_output_to_s3(context):
    ipynb_json = nbformat.writes(context.nb)
    _write_to_s3(context.output_ipynb_s3_uri, ipynb_json, context.s3)
    basic_html, _ = HTMLExporter(template_file='basic').from_notebook_node(context.nb)
    _write_to_s3(context.output_html_s3_uri, basic_html, context.s3) 
开发者ID:awslabs,项目名称:aws-iot-analytics-notebook-containers,代码行数:7,代码来源:iota_run_nb.py

示例12: convert_to_html

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def convert_to_html(nb):
    """Converts notebook dict to HTML with included CSS"""
    exporter = HTMLExporter()
    body, resources = exporter.from_notebook_node(nb)

    return body, resources 
开发者ID:ibleducation,项目名称:jupyter-edx-viewer-xblock,代码行数:8,代码来源:jupyter_utils.py

示例13: notebookExportToHtml

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def notebookExportToHtml(outputFilePath=None):
    """Export current notebook to HTML.
    If outputFilePath is not specified then filename will be generated from the notebook filename
    with current timestamp appended.
    It returns full path of the saved html file.
    It requires nbformat and nbconvert packages. You can use this command to install them:
        pip_install("nbformat nbconvert")
    """
    try:
      import nbformat
      from nbconvert import HTMLExporter
    except ModuleNotFoundError:
      import logging
      logging.error("notebookExportToHtml requires nbformat and nbconvert. They can be installed by running this command:\n\n    pip_install('nbformat nbconvert')\n")

    import datetime, json, os

    notebook_path = notebookPath()

    # Generate output file path from notebook name and timestamp (if not specified)
    if not outputFilePath:
      this_notebook_name = os.path.splitext(os.path.basename(notebook_path))[0]
      save_timestamp = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
      save_file_name = this_notebook_name + "_" + save_timestamp + ".html"
      notebooks_save_path = os.path.dirname(notebook_path)
      outputFilePath = os.path.join(notebooks_save_path, save_file_name)

    with open(notebook_path, mode="r") as f:
        file_json = json.load(f)
        
    notebook_content = nbformat.reads(json.dumps(file_json), as_version=4)

    html_exporter = HTMLExporter()
    (body, resources) = html_exporter.from_notebook_node(notebook_content)

    f = open(outputFilePath, 'wb')
    f.write(body.encode())
    f.close()

    return outputFilePath 
开发者ID:Slicer,项目名称:SlicerJupyter,代码行数:42,代码来源:files.py

示例14: gen_exporter

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def gen_exporter():
    config = TraitletsConfig()
    config.htmlexporter.preprocessors = [
        "nbconvert.preprocessors.extractoutputpreprocessor"
    ]
    html_exporter = HTMLExporter(config=config)
    html_exporter.template_file = "basic"
    return html_exporter 
开发者ID:hemanta212,项目名称:blogger-cli,代码行数:10,代码来源:ipynb_to_html.py

示例15: gen_tutorials

# 需要导入模块: import nbconvert [as 别名]
# 或者: from nbconvert import HTMLExporter [as 别名]
def gen_tutorials(repo_dir: str) -> None:
    """Generate HTML tutorials for captum Docusaurus site from Jupyter notebooks.

    Also create ipynb and py versions of tutorial in Docusaurus site for
    download.
    """
    with open(os.path.join(repo_dir, "website", "tutorials.json"), "r") as infile:
        tutorial_config = json.loads(infile.read())

    tutorial_ids = {x["id"] for v in tutorial_config.values() for x in v}

    for tid in tutorial_ids:
        print("Generating {} tutorial".format(tid))

        # convert notebook to HTML
        ipynb_in_path = os.path.join(repo_dir, "tutorials", "{}.ipynb".format(tid))
        with open(ipynb_in_path, "r") as infile:
            nb_str = infile.read()
            nb = nbformat.reads(nb_str, nbformat.NO_CONVERT)

        # displayname is absent from notebook metadata
        nb["metadata"]["kernelspec"]["display_name"] = "python3"

        exporter = HTMLExporter()
        html, meta = exporter.from_notebook_node(nb)

        # pull out html div for notebook
        soup = BeautifulSoup(html, "html.parser")
        nb_meat = soup.find("div", {"id": "notebook-container"})
        del nb_meat.attrs["id"]
        nb_meat.attrs["class"] = ["notebook"]
        html_out = JS_SCRIPTS + str(nb_meat)

        # generate html file
        html_out_path = os.path.join(
            repo_dir, "website", "_tutorials", "{}.html".format(tid)
        )
        with open(html_out_path, "w") as html_outfile:
            html_outfile.write(html_out)

        # generate JS file
        script = TEMPLATE.format(tid)
        js_out_path = os.path.join(
            repo_dir, "website", "pages", "tutorials", "{}.js".format(tid)
        )
        with open(js_out_path, "w") as js_outfile:
            js_outfile.write(script)

        # output tutorial in both ipynb & py form
        ipynb_out_path = os.path.join(
            repo_dir, "website", "static", "files", "{}.ipynb".format(tid)
        )
        with open(ipynb_out_path, "w") as ipynb_outfile:
            ipynb_outfile.write(nb_str)
        exporter = ScriptExporter()
        script, meta = exporter.from_notebook_node(nb)
        py_out_path = os.path.join(
            repo_dir, "website", "static", "files", "{}.py".format(tid)
        )
        with open(py_out_path, "w") as py_outfile:
            py_outfile.write(script) 
开发者ID:facebookresearch,项目名称:ClassyVision,代码行数:63,代码来源:parse_tutorials.py


注:本文中的nbconvert.HTMLExporter方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。