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


Python nbformat.reads方法代码示例

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


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

示例1: test_geoip_notebook

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def test_geoip_notebook(self):
        nb_path = Path(_NB_FOLDER).joinpath(_NB_NAME)
        abs_path = Path(_NB_FOLDER).absolute()

        with open(nb_path, "rb") as f:
            nb_bytes = f.read()
        nb_text = nb_bytes.decode("utf-8")
        nb = nbformat.reads(nb_text, as_version=4)
        ep = ExecutePreprocessor(timeout=600, kernel_name="python3")

        try:
            ep.preprocess(nb, {"metadata": {"path": abs_path}})
        except CellExecutionError:
            nb_err = str(nb_path).replace(".ipynb", "-err.ipynb")
            msg = f"Error executing the notebook '{nb_path}'.\n"
            msg += f"See notebook '{nb_err}' for the traceback."
            print(msg)
            with open(nb_err, mode="w", encoding="utf-8") as f:
                nbformat.write(nb, f)
            raise 
开发者ID:microsoft,项目名称:msticpy,代码行数:22,代码来源:test_geoip.py

示例2: download_notebook

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def download_notebook(tmpdir, request):
    notebook_url = request.param

    # check extension of file
    filename = os.path.basename(notebook_url)
    if not notebook_url.endswith('.ipynb'):
        raise ValueError(f'{filename} is not a Jupyter notebook.')

    # redirect notebook if notebook is located on nbviewer.jupyter.org
    if 'nbviewer' in notebook_url:
        r = requests.get(notebook_url)
        link = re.findall(
            '(?<=<a href=").+(?=" title="Download Notebook" ' 'download>)',
            r.content.decode('utf8'),
        )
        if len(link) > 0:
            notebook_url = link[0]

    # download notebook
    r = requests.get(notebook_url)

    nb = nbformat.reads(r.content.decode('utf8'), 4)
    nb['metadata'].update({'path': f'{tmpdir}'})

    return nb 
开发者ID:m-rossi,项目名称:jupyter-docx-bundler,代码行数:27,代码来源:conftest.py

示例3: notebook_view

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [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: __init__

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def __init__(self, node_or_path):
        if isinstance(node_or_path, string_types):
            path = urlparse(node_or_path).path
            if not os.path.splitext(path)[-1].endswith('ipynb'):
                raise Warning(
                    "Requires an '.ipynb' file extension. Provided path: '{}'".format(node_or_path)
                )
            self.path = node_or_path
            self.node = nbformat.reads(papermill_io.read(node_or_path), as_version=4)
        else:
            self.path = ""
            self.node = node_or_path

        # Memoized traits
        self._scraps = None
        self._outputs = None 
开发者ID:nteract,项目名称:scrapbook,代码行数:18,代码来源:models.py

示例5: read_source_script

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def read_source_script(filepath):
    """Read the contents of `filepath`

    Parameters
    ----------
    filepath: Str
        Absolute path to a Python file. Expected to end with '.py', or '.ipynb'

    Returns
    -------
    source: Str
        The contents of `filepath`"""
    if filepath.endswith(".ipynb"):
        with open(filepath, "r") as f:
            from nbconvert import PythonExporter
            import nbformat

            notebook = nbformat.reads(f.read(), nbformat.NO_CONVERT)
            exporter = PythonExporter()
            source, _ = exporter.from_notebook_node(notebook)
    else:
        with open(filepath, "r") as f:
            source = f.read()

    return source 
开发者ID:HunterMcGushion,项目名称:hyperparameter_hunter,代码行数:27,代码来源:parsing_utils.py

示例6: collect

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def collect(self):
        with self.fspath.open() as f:
            payload = f.read()
        self.notebook_folder = self.fspath.dirname
        try:
            # Ipython 3
            self.nb = reads(payload, 3)
        except (TypeError, NBFormatError):
            # Ipython 2
            self.nb = reads(payload, 'json')
        self.runner = NotebookRunner(self.nb)

        cell_num = 1

        for cell in self.runner.iter_code_cells():
            yield IPyNbCell(self.name, self, cell_num, cell)
            cell_num += 1 
开发者ID:zonca,项目名称:pytest-ipynb,代码行数:19,代码来源:plugin.py

示例7: sample_perf

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def sample_perf(nb, n=30):
    samples = pd.DataFrame(
        pd.np.NaN,
        index=pd.MultiIndex.from_product(
            (range(n), ['nbformat'] + JUPYTEXT_FORMATS), names=['sample', 'implementation']),
        columns=pd.Index(['size', 'read', 'write'], name='measure'))

    for i, fmt in samples.index:
        t0 = time.time()
        if fmt == 'nbformat':
            text = nbformat.writes(nb)
        else:
            text = jupytext.writes(nb, fmt)
        t1 = time.time()
        samples.loc[(i, fmt), 'write'] = t1 - t0
        samples.loc[(i, fmt), 'size'] = len(text)
        t0 = time.time()
        if fmt == 'nbformat':
            nbformat.reads(text, as_version=4)
        else:
            jupytext.reads(text, fmt)
        t1 = time.time()
        samples.loc[(i, fmt), 'read'] = t1 - t0
    return samples 
开发者ID:mwouts,项目名称:jupytext,代码行数:26,代码来源:Benchmarking Jupytext.py

示例8: md_to_notebook

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def md_to_notebook(text):
    """Convert a Markdown text to a Jupyter notebook, using Pandoc"""
    tmp_file = tempfile.NamedTemporaryFile(delete=False)
    tmp_file.write(text.encode("utf-8"))
    tmp_file.close()

    pandoc(
        u"--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs",
        tmp_file.name,
        tmp_file.name,
    )

    with open(tmp_file.name, encoding="utf-8") as opened_file:
        notebook = ipynb_reads(opened_file.read(), as_version=4)
    os.unlink(tmp_file.name)

    return notebook 
开发者ID:mwouts,项目名称:jupytext,代码行数:19,代码来源:pandoc.py

示例9: divine_format

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def divine_format(text):
    """Guess the format of the notebook, based on its content #148"""
    try:
        nbformat.reads(text, as_version=4)
        return "ipynb"
    except nbformat.reader.NotJSONError:
        pass

    lines = text.splitlines()
    for comment in ["", "#"] + _COMMENT_CHARS:
        metadata, _, _, _ = header_to_metadata_and_cell(lines, comment)
        ext = (
            metadata.get("jupytext", {}).get("text_representation", {}).get("extension")
        )
        if ext:
            return ext[1:] + ":" + guess_format(text, ext)[0]

    # No metadata, but ``` on at least one line => markdown
    for line in lines:
        if line == "```":
            return "md"

    return "py:" + guess_format(text, ".py")[0] 
开发者ID:mwouts,项目名称:jupytext,代码行数:25,代码来源:formats.py

示例10: load_ipynb_text

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def load_ipynb_text(text: str):
    try:
        return nbformat.reads(text, as_version=4)
    except AttributeError as e:
        raise nbformat.reader.NotJSONError(msgfy.to_error_message(e))
    except OSError as e:
        _schema_not_found_error_handler(e)
        raise 
开发者ID:thombashi,项目名称:sqlitebiter,代码行数:10,代码来源:_ipynb_converter.py

示例11: load_ipynb_url

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def load_ipynb_url(url: str, proxies: Optional[Dict]) -> Tuple:
    response = retryrequests.get(url, proxies=proxies)
    response.raise_for_status()

    try:
        return (nbformat.reads(response.text, as_version=4), len(response.content))
    except OSError as e:
        _schema_not_found_error_handler(e)
        raise 
开发者ID:thombashi,项目名称:sqlitebiter,代码行数:11,代码来源:_ipynb_converter.py

示例12: _read_notebook

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def _read_notebook(self, blob):
        """
        Reads a notebook file from GCS blob.
        :param blob: :class:`google.cloud.storage.Blob` instance.
        :return: :class:`nbformat.notebooknode.NotebookNode` instance.
        """
        data = blob.download_as_string().decode("utf-8")
        nb = nbformat.reads(data, as_version=4)
        self.mark_trusted_cells(nb, self._get_blob_path(blob))
        return nb 
开发者ID:src-d,项目名称:jgscm,代码行数:12,代码来源:__init__.py

示例13: test_save_notebook

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def test_save_notebook(self):
        nb = nbformat.reads(self.NOTEBOOK, 4)
        self.contents_manager.save({
            "type": "notebook",
            "content": nb
        }, self.path("test.ipynb"))
        bucket = self.bucket
        blob = bucket.blob("test.ipynb")
        self.assertTrue(blob.exists())
        try:
            self.assertEqual(blob.download_as_string(), self.NOTEBOOK.encode())
        finally:
            blob.delete() 
开发者ID:src-d,项目名称:jgscm,代码行数:15,代码来源:test.py

示例14: _read_notebook

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def _read_notebook(self, path, as_version=4):
        """Read a notebook from a path."""
        nb, format = self._read_file(path, 'text')
        return nbformat.reads(nb, as_version=as_version) 
开发者ID:jpmorganchase,项目名称:jupyter-fs,代码行数:6,代码来源:fsmanager.py

示例15: _load_nb_to_dict

# 需要导入模块: import nbformat [as 别名]
# 或者: from nbformat import reads [as 别名]
def _load_nb_to_dict(self, nb_path):
        """Loads the students autograded notebook"""
        if os.path.exists(nb_path):
            with open(nb_path, 'r') as f:
                raw = f.read()

        # NOTE: as_version should be...?
        nb = nbformat.reads(raw, as_version=4)
        return nb 
开发者ID:ibleducation,项目名称:jupyter-edx-grader-xblock,代码行数:11,代码来源:container.py


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