尽管 try- except block ,Python 脚本仍以退出代码 255 退出

标签 python exception try-catch

我正在尝试在我的脚本中构建一些异常处理,然后再将其发送给用户试用。为了实现这一目标,我尝试运行 try- except block 来捕获我认为可能发生的错误。

例如,代码使用 API 与另一个软件进行交互。该软件依赖于计算机上安装的硬件许可证(USB 加密狗),否则该软件无法通过 Python 访问,并且脚本会以退出代码 255 退出。代码示例如下。

    code-to-activate-licence
except Exception as e:
     warn-user-of-error

我希望 try-except block 获取退出代码并执行代码的 except 部分。但是,我认为尝试激活许可证似乎不会引发错误,而是给出非零退出代码,它似乎不会被 try- except block 捕获。有没有办法在实际退出脚本之前捕获此退出代码?

最佳答案

您正在使用except Exception as e:然而图书馆正在调用 sys.exit()这引发了 SystemExit其类型为 BaseException而不是标准ExceptionException包含所有非系统退出异常。

您需要显式捕获 SystemExit以便打断它。

来自[docs] :

exception SystemExit

This exception is raised by the sys.exit() function. It inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception.

异常异常

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.

在代码中它看起来像:

try:
    somecode()
except Exception as e:
    do_something_with_exception(e)
except SystemExit as x:
    do_something_not_exit(x)

关于尽管 try- except block ,Python 脚本仍以退出代码 255 退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55924660/

相关文章:

android - 如何检测Android出现静默故障的原因?

java - 没有 catch 或 finally block 的嵌套 try block

try-catch - "catch"后面的部分叫什么?

python - 使用类别和子类别优化 Django 中的数据库查询

python - res_similarity() 函数的参数

python - django 1.2.5 上管理员登录被禁止 403 csrf 验证

java - 如何处理java代码的错误

python - py.test 不从数据库中提取数据

java - 定时器错误 java.lang.IllegalStateException

python - django 无法打开数据库文件