Last active
May 15, 2018 08:14
-
-
Save ayuLiao/5c0f5934368216c0805a511c9ac95345 to your computer and use it in GitHub Desktop.
当调用网络请求方法或其他易报错的方法时,可以尝试多次调用,再每次失败后,再次调用它,为了让其正常运行
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def retry(f, n_attempts=3): | |
# 包装函数,在函数异常时尝试多次调用,这里是尝试3次 | |
def wrapper(*args, **kwargs): | |
for i in range(n_attempts): | |
try: | |
return f(*args, **kwargs) | |
except Exception: | |
if i == n_attempts - 1: | |
raise | |
return wrapper | |
# 金融数据包 | |
import tushare as ts | |
# 避免某次调用get_hs300s方法失败 | |
hs300 = retry(ts.get_hs300s)() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment