首页 > 解决方案 > 对于 IPython 运行魔法,忽略 SystemExist 的选项似乎不适用于模块

问题描述

%run魔术-e选项状态的文档:

忽略正在运行的脚本中的 sys.exit() 调用或 SystemExit 异常。如果使用 IPython 运行单元测试,这将特别有用,单元测试总是通过 sys.exit() 调用退出。在这种情况下,您对测试结果的输出感兴趣,而不是查看 unittest 模块的回溯。

这在运行脚本时有效,但在运行模块时似乎不起作用。因此,当我键入%run -e -m pytest时,由于 pytest 引发的测试失败,我仍然会得到回溯,SystemExit这是上面文档中提到的情况,-e旨在解决。我知道我会打字!pytest但我不想等到pytest完成后再开始查看结果,而且我还想将当前目录添加到模块搜索路径中。

我在 Spyder 中运行 IPython,但如果我从 Windows 命令提示符运行 IPython,行为是相同的。我有什么方法可以做我想做的事并避免分散注意力的回溯吗?

%run -m pytest我从 spyder ipython 控制台运行了以下测试

import pytest

def test_fail():
    assert 0

输出是:

============================= test session starts =============================
platform win32 -- Python 3.7.7, pytest-5.4.1, py-1.8.1, pluggy-0.13.1
rootdir: D:\home\shane\temp\pytest
collected 1 item

test_dummy.py F                                                          [100%]

================================== FAILURES ===================================
__________________________________ test_fail __________________________________

    def test_fail():
>       assert 0
E       AssertionError

test_dummy.py:21: AssertionError
=========================== short test summary info ===========================
FAILED test_dummy.py::test_fail - AssertionError
============================== 1 failed in 0.03s ==============================
Traceback (most recent call last):

  File "c:\opt\python37\lib\runpy.py", line 205, in run_module
    return _run_module_code(code, init_globals, run_name, mod_spec)

  File "c:\opt\python37\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)

  File "c:\opt\python37\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)

  File "c:\opt\python37\lib\site-packages\pytest\__main__.py", line 7, in <module>
    raise SystemExit(pytest.main())

SystemExit: ExitCode.TESTS_FAILED

标签: python-3.xipythonpytestspyder

解决方案


推荐阅读