有没有办法防止从 sys.exit() 引发的 SystemExit 异常被捕获? [英] Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught?

查看:35
本文介绍了有没有办法防止从 sys.exit() 引发的 SystemExit 异常被捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档说调用 sys.exit() 会引发 SystemExit 异常,该异常可以在外部级别捕获.我有一种情况,我想明确且毫无疑问地从测试用例内部退出,但是 unittest 模块捕获 SystemExit 并阻止退出.这通常很好,但我尝试处理的特定情况是我们的测试框架检测到它被配置为指向非测试数据库.在这种情况下,我想退出并阻止运行任何进一步的测试.当然,由于 unittest 捕获了 SystemExit 并愉快地继续前进,这让我感到沮丧.

The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database. In this case I want to exit and prevent any further tests from being run. Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me.

到目前为止,我想到的唯一选择是使用 ctypes 或类似的东西直接调用 exit(3) ,但这对于应该非常简单的事情来说似乎是一个非常愚蠢的黑客.

The only option I have thought of so far is using ctypes or something similar to call exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.

推荐答案

您可以拨打 os._exit() 直接退出,不抛出异常:

You can call os._exit() to directly exit, without throwing an exception:

import os
os._exit(1)

这会绕过所有 python 关闭逻辑,例如 atexit 模块,并且不会运行您在这种情况下试图避免的异常处理逻辑.参数是进程将返回的退出代码.

This bypasses all of the python shutdown logic, such as the atexit module, and will not run through the exception handling logic that you're trying to avoid in this situation. The argument is the exit code that will be returned by the process.

这篇关于有没有办法防止从 sys.exit() 引发的 SystemExit 异常被捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆