gpt4 book ai didi

python - 在异常时重复 Python 函数调用?

转载 作者:太空狗 更新时间:2023-10-29 18:16:33 24 4
gpt4 key购买 nike

大家好,我正在做一个数据抓取项目,我正在寻找一种干净的方法来在引发异常时重复函数调用。

伪代码:

try:
myfunc(x)
except myError:
###try to call myfunc(x) again Y number of times,
until success(no exceptions raised) otherwise raise myError2

我意识到这根本不是最佳实践,但我正在研究许多不可靠的不同代码/网络层,我无法实际调试它们。

现在我正在用大量的 try\except block 来完成这个,这让我的眼睛流血了。

优雅的想法有人吗?

最佳答案

要精确地执行您想要的操作,您可以执行以下操作:

import functools
def try_x_times(x, exceptions_to_catch, exception_to_raise, fn):
@functools.wraps(fn) #keeps name and docstring of old function
def new_fn(*args, **kwargs):
for i in xrange(x):
try:
return fn(*args, **kwargs)
except exceptions_to_catch:
pass
raise exception_to_raise
return new_fn

然后你只需将旧函数包装在这个新函数中:

#instead of
#risky_method(1,2,'x')
not_so_risky_method = try_x_times(3, (MyError,), myError2, risky_method)
not_so_risky_method(1,2,'x')

#or just
try_x_times(3, (MyError,), myError2, risky_method)(1,2,'x')

关于python - 在异常时重复 Python 函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4766556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com