qaviton处理程序
qaviton-handlers的Python项目详细描述
Qaviton处理程序
错误处理实用程序
安装
pip install --upgrade qaviton_handlers
要求
- Python 3.6+
特点
- 重试装饰器✓
- 使用上下文✓重试
- 尝试函数✓
- 捕捉错误✓
- 简单异常包装器✓
使用
^{pr2}$重试装饰器
fromqaviton_handlers.try_decoratorimportretry@retry()deffoo():n=int('1'+input('select number:'))print(n)foo()
使用上下文重试
fromqaviton_handlers.try_contextimportretrywithretry()astrying:whiletrying:withtrying:print("Attempt #%d of %d"%(trying.attempt,trying.attempts))raise
使用不同的try wrapper函数
fromqaviton_handlers.try_functionsimporttry_to,try_or_none,multi_try,multi_try_no_breakdeffoo(a=0):print(float(a+input("select number:")))# simply trytry_to(foo,1)try_to(foo,2)try_to(foo,3)
# get the errorerror=try_to(foo,4)iferror:print(error)# if error occurrediftry_to(foo,5):try_to(foo,5)
# try with key argumentsr=try_to(lambdaa,b,c:a*b*c,1,kwargs={'b':2,'c':3})print(r)
# try to get a numbernumber=try_or_none(lambdaa:float(a+input("select number:")),6)ifnumber:print(number)
# try many functions, return a list of results, or an error# if an error occurred, the multi try stopsmulti_try(lambda:foo(10),lambda:foo(11),)# specify errors to ignoreresponse=multi_try(lambda:foo(13),lambda:foo(14),exceptions=Exception,)# handle the errorresponse=multi_try(lambda:foo(13),lambda:foo(14),)ifisinstance(response,Exception):...
# try many functions, return a list of results, some may be errors# if an error occurred, the multi try continuesmulti_try_no_break(lambda:foo(8),lambda:foo(9),lambda:foo(0),)
现在忽略错误,以便以后处理它们
fromqaviton_handlers.catchimportCatchfromqaviton_handlers.utils.errorimportErrorcatch=Catch(store=True)# catch an errortry:1+'1'exceptExceptionase:catch(e)# a cleaner syntaxwithcatch:1+'1'2+'2'# ignore the errorwithCatch():5*'e'print(f"caught {catch.count} errors")print(f"caught first {catch.first}")print(f"caught last {catch.last}")# make your own CatchclassMyCatch(Catch):defhandler(self,e):self.stack.add(Error(e))ifself.log:self.log.warning(f"I caught {e}")returnself
- 项目
标签: