在pytest中使用键盘中断钩子

Using the keyboard interrupt hook in pytest

我正在尝试捕获键盘中断,以便我可以手动调用 tearDown。我知道这存在:

def pytest_keyboard_interrupt(excinfo):
    """ called for keyboard interrupt. """

从这里开始:http://doc.pytest.org/en/latest/_modules/_pytest/hookspec.html

但是,我不知道如何在我的测试中使用它 it/override。我是 pytest 的新手。

有人有这方面的经验吗?

您必须创建 conftest.py 文件并覆盖该文件中的 pytest_keyboard_interrupt

# content of conftest.py

def pytest_keyboard_interrupt(excinfo):
    # Calling tearDown.

注意: 不是重复的问题,但答案可能完全适用于您的情况:py.test: get KeyboardInterrupt to call teardown