在python中,如果在被调用函数中发生了某个事件,则有一种不返回到调用者函数的方法。例如,...
def acquire_image(sdkobject):
ret = sdkobject.PrepareAcquisition()
error_check(ret)
ret = sdkobject.StartAcquisition()
error_check(ret)
error_check是一个用于检查返回代码以查看sdk调用是否有错误的函数。如果这是一条错误消息,那么我不希望返回并获取图像,而是转到另一个函数以重新初始化sdk并从头开始。有pythonic的方法吗?
最佳答案
如果存在问题,请让error_check
函数引发异常(例如SDKError
),然后在while循环中运行所有命令。
class SDKError(Exception):
pass
# Perhaps define a separate exception for each possible
# error code, and make a dict that maps error codes to the
# appropriate exception.
class SDKType1Error(SDKError):
pass
class SDKType5Error(SDKError):
pass
sdk_errors = {
1: SDKType1Error,
5: SDKType5Error,
}
# Either return, if there was no error, or raise
# the appropriate exception
def error_check(return_code):
if return_code == 0:
return # No error
else:
raise sdk_errors[return_code]
# Example of how to deal with specific SDKErrors subclasses, or a generic
# catch-all SDKError
def acquire_image(sdkobject):
while True:
try:
# initialize sdk here
error_check(sdkobject.PrepareAcquisition())
error_check(sdkobject.StartAcquisition())
except SDKType1Error:
# Special handling for this error
except SDKError:
pass
else:
break
关于python - 如何不返回调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23562555/