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

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

问题描述

文档说,调用sys.exit()会引发一个可以在外部级别被捕获的SystemExit异常。我有一种情况,我想要毫无疑问地从测试用例中退出,但是unittest模块捕获SystemExit并阻止退出。这通常很好,但是我正在尝试处理的具体情况是我们的测试框架检测到它被配置为指向非测试数据库的情况。在这种情况下,我想退出并防止进一步的测试运行。当然,由于unittest陷阱了SystemExit,而是以这种方式继续快乐,它正在阻止我。



目前为止我所想到的唯一选择是使用ctypes或类似的东西直接呼叫退出(3),但这似乎是非常简单的一个非常简单的事情。

解决方案

你可以打电话 os._exit()直接退出,而不会抛出异常:

  import os 
os._exit(1)
pre>

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


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.

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.

解决方案

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

  import os
  os._exit(1)

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天全站免登陆