在pytest中运行Jupyter笔记本测试。 OSERROR

时间:2018-05-18 10:18:01

标签: python jupyter-notebook jupyter pytest

我有一个python测试,它应该运行Jupyter笔记本文件并检查它是否有错误。 当我运行它时,它会返回错误:OSError: [Errno 8] Exec format error: './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 == []

1 个答案:

答案 0 :(得分:3)

您的args错了。你基本上所谓的是

$ ./file.ipynb tempfile.ipynb nbconvert --to notebook \
    --execute --ExecutePrerocessor.timeout=60 --output

这不起作用,因为file.ipynb不是可执行文件。您需要调用jupyter

$ jupyter nbconvert ./file.ipynb --output tempfile.ipynb --to notebook \
    --execute --ExecutePrerocessor.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