有没有办法让 py.test 忽略子进程上引发的 SystemExit?

Ric*_*mes 6 python systemexit multiprocessing pytest

我正在测试一个包含以下代码片段的 Python 模块。

        r, w = os.pipe()
        pid = os.fork()
        if pid:
            os.close(w)        # use os.close() to close a file descriptor
            r = os.fdopen(r)   # turn r into a file object
            # read serialized object from ``r`` and persists onto storage medium
            self.ofs.put_stream(bucket, label, r, metadata)
            os.waitpid(pid, 0) # make sure the child process gets cleaned up
        else:
            os.close(r)
            w = os.fdopen(w, 'w')
            # serialize object onto ``w``
            pickle.dump(obj, w)
            w.close()
            sys.exit(0)
        return result
Run Code Online (Sandbox Code Playgroud)

所有测试都通过了,但是有困难sys.exit(0)。执行时sys.exit(0),它会引发SystemExit,它被拦截py.test并在控制台中报告为错误。

我不详细了解py.test内部的作用,但看起来它会继续进行并最终忽略子进程引发的此类事件。最后,所有测试都通过了,这很好。

但我希望在控制台中有一个干净的输出。

有没有一种方法可以py.test产生干净的输出?

供你参考:

  • Debian Jessie,内核 3.12.6
  • Python 2.7.6
  • pytest 2.5.2

谢谢 :)

Ric*_*mes 3

(回答我自己的问题)

您可以终止执行,而不会引发与这些事件相关的信号。sys.exit(n)因此,不要使用 ,而是使用os._exit(n),其中n是所需的状态代码。

例子:

import os
os._exit(0)
Run Code Online (Sandbox Code Playgroud)

鸣谢: 有没有办法防止捕获 sys.exit() 引发的 SystemExit 异常?