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


Python nbconvert.HTMLExporter类代码示例

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


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

示例1: nb_to_html

def nb_to_html(root, template='basic', version=4, timeout=600, kernel='python3'):
    '''
    This functions executes a Jupyter notebook and creates the related
    HTML file.

    Args:
        root (str): name of the file without the .ipynb extension
        template (str): name of the template (to be in the current folder as template.tpl)
        version (int): version of the notebook
        timeout (float): maximum time spent per cell
        kernel (str)

    Returns:
        None

    The function executes root.ipynb into root_exe.ipynb and creates the file root.html.
    '''
    with open(root + '.ipynb') as f:
        nb = nbformat.read(f, as_version=version)

    ep = ExecutePreprocessor(timeout=timeout, kernel_name=kernel)
    ep.preprocess(nb, {'metadata': {'path': '.'}})

    with open(root + '_exe.ipynb', 'wt') as f:
        nbformat.write(nb, f)

    html_exporter = HTMLExporter()
    html_exporter.template_file = template

    with open(root + '_exe.ipynb', mode='r') as f:
        notebook = nbformat.reads(''.join(f.readlines()), as_version=version)
        (body, _) = html_exporter.from_notebook_node(notebook)
        codecs.open(root + '.html', 'w', encoding='utf-8').write(body)
开发者ID:PetitLepton,项目名称:design,代码行数:33,代码来源:nb_to_report.py

示例2: bundle_notebook

def bundle_notebook(vid, fileid):
    """Return a file from the bundle"""
    from ambry.orm.file import File
    import nbformat
    from traitlets.config import Config
    from nbconvert import HTMLExporter

    b = aac.library.bundle(vid)

    nbfile = b.build_source_files.file_by_id(fileid)

    notebook = nbformat.reads(nbfile.unpacked_contents, as_version=4)

    html_exporter = HTMLExporter()
    html_exporter.template_file = 'basic'

    (body, resources) = html_exporter.from_notebook_node(notebook)

    cxt = dict(
        vid=vid,
        b=b,
        fileid=fileid,
        nbfile=nbfile,
        notebooks=b.build_source_files.list_records(File.BSFILE.NOTEBOOK),
        notebook=notebook,
        notebook_html=body,
        **aac.cc

    )

    return aac.render('bundle/notebook.html', **cxt)
开发者ID:CivicKnowledge,项目名称:ambry-ui,代码行数:31,代码来源:views.py

示例3: build_iab_main

def build_iab_main(input_dir, output_dir, out_format, ext, css=None):
    """ Convert md sources to readable book content, maintaining dir structure.

        A few additional processing steps happen here:
         * Add Table of Contents to the top of each section.
         * Create links from sha1 aliases.

        Parameters
        ----------
        input_dir : str
            Root path for the markdown files.
        output_dir : str
            Root path for the output files.
        out_format : str
            The ipymd format that output files should be written in (for example,
            ``notebook``).
        ext : str
            The extension to use for output files.

    """
    # Walk the input root directory. We only care about root and files
    # inside this loop (nothing happens with dirs).
    for unit_number, (unit, chapters) in enumerate(input_dir):
        # Iterate over the files in the current root.
        if unit_number == 0:
            unit_path = ''
        else:
            unit_path = str(unit_number) + '/'
        for chapter_number, content_md in enumerate(chapters):
            if chapter_number == 0:
                chapter_path = 'index'
            else:
                chapter_path = str(chapter_number)
            path = '%s%s' % (unit_path, chapter_path)
            # Convert it from markdown
            output_s = ipymd.convert(content_md, from_='markdown', to='notebook')
            # define the output filepath
            output_fp = get_output_fp(output_dir, path, ext)
            try:
                os.makedirs(os.path.split(output_fp)[0])
            except OSError:
                pass

            # write the output ipynb
            nbformat.write(output_s, output_fp)

    if out_format == 'html' or out_format == 's3':
        c = Config()
        c.ExecutePreprocessor.timeout = 600
        html_exporter = HTMLExporter(preprocessors=['nbconvert.preprocessors.execute.ExecutePreprocessor'],
                                     config=c)

        for root, dirs, files in os.walk(output_dir):
            if css:
                shutil.copy(css, os.path.join(root, 'custom.css'))
            for f in files:
                html_out, _ = html_exporter.from_filename(os.path.join(root, f))
                output_fn = os.path.splitext(f)[0] + ext
                output_fp = os.path.join(root, output_fn)
                open(output_fp, 'w').write(html_out)
开发者ID:gregcaporaso,项目名称:build-iab,代码行数:60,代码来源:util.py

示例4: execute

    def execute(self):
        print("Cleaning lowfat/reports/html ...")
        old_reports = os.listdir("lowfat/reports/html")
        for old_report in old_reports:
            print("- Removing lowfat/reports/html/{}".format(old_report))
            os.remove("lowfat/reports/html/{}".format(old_report))
        print("Cleaning of lowfat/reports/html is complete.")

        notebook_filenames = os.listdir("lowfat/reports")

        for notebook_filename in notebook_filenames:
            if not notebook_filename.endswith(".ipynb"):
                continue

            print("Processing lowfat/reports/{}".format(notebook_filename))

            # Based on Executing notebooks, nbconvert Documentation by Jupyter Development Team.
            # https://nbconvert.readthedocs.io/en/latest/execute_api.html
            with open("lowfat/reports/{}".format(notebook_filename)) as file_:
                notebook = nbformat.read(file_, as_version=4)

                # Kernel is provided by https://github.com/django-extensions/django-extensions/
                execute_preprocessor = ExecutePreprocessor(timeout=600, kernel_name='django_extensions')
                execute_preprocessor.preprocess(notebook, {'metadata': {'path': '.'}})

                html_exporter = HTMLExporter()
                html_exporter.template_file = 'basic'

                (body, dummy_resources) = html_exporter.from_notebook_node(notebook)

                with open('lowfat/reports/html/{}.html'.format(notebook_filename), 'wt') as file_:
                    file_.write(body)
开发者ID:softwaresaved,项目名称:fat,代码行数:32,代码来源:report.py

示例5: update_jupyter

 def update_jupyter(self, s, keywords):
     '''Update @jupyter node in the vr pane.'''
     pc = self
     c = pc.c
     if pc.must_change_widget(QtWebKitWidgets.QWebView):
         # g.trace('===== instantiating QWebView')
         w = QtWebKitWidgets.QWebView()
         n = c.config.getInt('qweb_view_font_size')
         if n:
             settings = w.settings()
             settings.setFontSize(settings.DefaultFontSize, n)
         pc.embed_widget(w)
         assert(w == pc.w)
     else:
         w = pc.w
     url = g.getUrlFromNode(c.p)
     if url and nbformat:
         s = urlopen(url).read().decode()
         try:
             nb = nbformat.reads(s, as_version=4)
             e = HTMLExporter()
             (s, junk_resources) = e.from_notebook_node(nb)
         except nbformat.reader.NotJSONError:
             # Assume the result is html.
             pass
     elif url:
         s = 'can not import nbformt: %r' % url
     else:
         s = g.u('')
     if isQt5:
         w.hide() # This forces a proper update.
     w.setHtml(s)
     w.show()
     c.bodyWantsFocusNow()
开发者ID:satishgoda,项目名称:leo-editor,代码行数:34,代码来源:viewrendered.py

示例6: export_notebook_to_html

def export_notebook_to_html(notebook_fp, output_dir):
    nb = read_in_notebook(notebook_fp)
    html_exporter = HTMLExporter()
    body, resources = html_exporter.from_notebook_node(nb)
    _, notebook_name, _ = get_file_name_pieces(notebook_fp)
    out_fp = make_file_path(output_dir, notebook_name, ".html")
    with open(out_fp, "w", encoding="utf8") as f:
        f.write(body)
开发者ID:christineyi,项目名称:jupyter-genomics,代码行数:8,代码来源:notebook_runner.py

示例7: export_notebook_to_html

def export_notebook_to_html(notebook, datestamp, mark_as_latest=True):
    html_exporter = HTMLExporter()
    html, _resources = html_exporter.from_notebook_node(notebook)
    output_path = get_monitoring_notebook_output_path(datestamp, ext='html')
    with open(output_path, 'wt') as outfile:
        outfile.write(html)
    if mark_as_latest:
        latest_notebook_path = get_monitoring_notebook_output_path('latest', ext='html')
        copyfile(output_path, latest_notebook_path)
开发者ID:adaptive-learning,项目名称:robomission,代码行数:9,代码来源:export_monitoring_notebook.py

示例8: output_HTML

def output_HTML(read_file, output_file):
    from nbconvert import HTMLExporter
    import codecs
    import nbformat
    exporter = HTMLExporter()
    # read_file is '.ipynb', output_file is '.html'
    output_notebook = nbformat.read(read_file, as_version=4)
    output, resources = exporter.from_notebook_node(output_notebook)
    codecs.open(output_file, 'w', encoding='utf-8').write(output)
开发者ID:BenJamesbabala,项目名称:Wind-Speed-Analysis,代码行数:9,代码来源:lib_loader.py

示例9: convert_nb_html

def convert_nb_html(nb):
    """
    Convert a notebooks output to HTML
    """
    nb = run_notebook(nb)
    config = Config({'HTMLExporter': {'default_template': 'basic'}})
    exportHtml = HTMLExporter(config=config)
    html, resources = exportHtml.from_notebook_node(nb)
    soup = BeautifulSoup(html)
    filters = ["output", "text_cell_render border-box-sizing rendered_html"]
    return ''.join(map(str, soup.findAll("div", {"class": filters})))
开发者ID:zimmerst,项目名称:Flasked-Notebooks,代码行数:11,代码来源:run_ipynb.py

示例10: write_html

 def write_html(self):
     print("writing", self.html)
     html_exporter = HTMLExporter()
     html_exporter.template_file = 'full'
     # do a deeo copy to any chance of overwriting the original notebooks
     content = copy.deepcopy(self.content)
     content.cells = content.cells[2:-1]
     content.cells[0].source = "# " + self.numbered_title
     (body, resources) = html_exporter.from_notebook_node(content)
     with open(self.html, 'w') as f:
         f.write(body)
开发者ID:jckantor,项目名称:CBE20255,代码行数:11,代码来源:__main__.py

示例11: render

def render(file):
    """Generate the result HTML."""
    fp = file.open()
    content = fp.read()
    fp.close()

    notebook = nbformat.reads(content.decode('utf-8'), as_version=4)

    html_exporter = HTMLExporter()
    html_exporter.template_file = 'basic'
    (body, resources) = html_exporter.from_notebook_node(notebook)
    return body, resources
开发者ID:hachreak,项目名称:invenio-previewer,代码行数:12,代码来源:ipynb.py

示例12: preview

    def preview(self, filepath):
        """
        Preview a notebook store in the Storage
        :param filepath: Path to the notebook to preview on Storage

        :return a notebook in html format
        """
        self.log.debug("Make a Html preview of notebook '%s'" % filepath);
        nb = self.read(filepath);
        html_conveter = HTMLExporter()
        (body, resources) = html_conveter.from_notebook_node(nb)
        return body;
开发者ID:Valdimus,项目名称:nbshared,代码行数:12,代码来源:storage.py

示例13: _nbconvert_to_html

    def _nbconvert_to_html(cls, page):
        """Use nbconvert to render a notebook as HTML.
        
        Strip the headings from the first markdown cell to avoid showing the 
        page title twice on the blog.
        """
        if page["cells"] and page["cells"][0]["cell_type"] == "markdown":
            source = page["cells"][0]["source"]
            page["cells"][0]["source"] = re.sub("#+.*\n", "", source, re.MULTILINE)

        e = HTMLExporter()
        e.template_file = "basic"
        return e.from_notebook_node(page)[0]
开发者ID:parente,项目名称:blog,代码行数:13,代码来源:generate.py

示例14: post

        def post(self): 
          id=self.get_argument("path")
          print id
          db=create_engine('postgresql://postgres:[email protected]/ishtar')
        
          fileContent=reads_base64(pgquery.get_file(db, "share", id, include_content=True)['content'])
          #notebook= nbformat.reads(fileContent, as_version=4)
          notebook=fileContent
          db.dispose()
          html_exporter = HTMLExporter()
          html_exporter.template_file = 'basic'

          (body, resources) = html_exporter.from_notebook_node(notebook)
          self.write(body)
开发者ID:albanatita,项目名称:GilgameshServer,代码行数:14,代码来源:serverHub.py

示例15: as_html

    def as_html(self, file):
        with File().open(file) as fp:
            notebook = nbformat.reads(fp.read().decode(), as_version=4)

        exporter = HTMLExporter()
        #exporter.template_file = 'basic'

        (body, resources) = exporter.from_notebook_node(notebook)

        def stream():
            cherrypy.response.headers['Content-Type'] = 'text/html'
            yield body

        return stream
开发者ID:OpenChemistry,项目名称:mongochemserver,代码行数:14,代码来源:rest.py


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