我正在尝试在我的脚本中构建一些异常处理,然后再将其发送给用户试用。为了实现这一目标,我尝试运行 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
而不是标准Exception
。 Exception
包含所有非系统退出异常。
您需要显式捕获 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.
异常异常
block 引用>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/