Python 在pytest中运行Jupyter笔记本测试。奥瑟罗

Python 在pytest中运行Jupyter笔记本测试。奥瑟罗,python,jupyter-notebook,jupyter,pytest,Python,Jupyter Notebook,Jupyter,Pytest,我有一个python测试,它应该运行Jupyter笔记本文件并检查它是否有错误。 当我运行它时,它返回一个错误:OSError:[Errno 8]Exec格式错误:'./file.ipynb' 有人知道如何解决这个问题吗 我在类似问题中发现的似乎与我的情况不同 我的代码如下: import os import subprocess import tempfile import nbformat def _notebook_run(path): """Execute a notebo

我有一个python测试,它应该运行Jupyter笔记本文件并检查它是否有错误。 当我运行它时,它返回一个错误:
OSError:[Errno 8]Exec格式错误:'./file.ipynb'

有人知道如何解决这个问题吗

我在类似问题中发现的似乎与我的情况不同

我的代码如下:

import os
import subprocess
import tempfile

import nbformat


def _notebook_run(path):
    """Execute a notebook via nbconvert and collect output.
       :returns (parsed nb object, execution errors)
    """
    dirname, __ = os.path.split(path)
    os.chdir(dirname)
    with tempfile.NamedTemporaryFile(suffix=".ipynb") as fout:
        args = [path, fout.name, "nbconvert", "--to", "notebook", "--execute",
          "--ExecutePreprocessor.timeout=60",
          "--output"]
        subprocess.check_call(args)

        fout.seek(0)
        nb = nbformat.read(fout, nbformat.current_nbformat)

    errors = [output for cell in nb.cells if "outputs" in cell
                     for output in cell["outputs"]\
                     if output.output_type == "error"]

    return nb, errors

def test_ipynb():
    nb, errors = _notebook_run('./file.ipynb')
    assert errors == []

您的
参数
错误。你所说的基本上是

$./file.ipynb tempfile.ipynb nbconvert--到笔记本电脑\
--execute--ExecuteProcessor.timeout=60--output
这不起作用,因为
file.ipynb
不是可执行文件。您需要调用
jupyter

$jupyter nbconvert./file.ipynb——输出tempfile.ipynb——到笔记本电脑\
--execute--ExecuteProcessor.timeout=60
翻译成Python
args
,例如:

import shutil

...

jupyter_exec = shutil.which('jupyter')
if jupyter_exec is not None:
    args = [jupyter_exec, "nbconvert", path, 
            "--output", fout.name, 
            "--to", "notebook", 
            "--execute", "--ExecutePreprocessor.timeout=60"]
    subprocess.check_call(args)
else:
    # jupyter not installed or not found in PATH

非常感谢很高兴我能帮忙!难道你不知道如何通过这种方式运行jupyter笔记本获得输出吗?例如,当我运行notebook时,它给出的输出为1,但当我运行此代码时,它给出的文件包含大量信息,而不是运行notebook的结果。嗯,您能提供更多信息吗?您是指
子流程
返回的退出代码?如果使用
subprocess.call
,它将返回退出代码,而
subprocess.check\u call
将在退出代码为零时不返回任何内容,否则将引发异常。