"""上面這個裝飾器函式來自某位大神之手,先膜拜一下,它能自動為被裝飾的函式加上retry功能。:param delays: an iterable object the defines num of seconds between reties, also indicating num of retries.
default: retry 3 times, waiting 1/5/30 seconds.
:param exceptions: specifies exceptions that trigger retry. otherwise no actions will be taken. default: all exceptions.
:param report: an callable object, e.g print or logger method. default: report nothing.
"""def retry(delays=(3, 10, 15), exceptions=(exception, ), report=lambda *args: none):
@functools.wraps(function)
problems =
for delay in itertools.chain(delays, [none]):
try:
return function(*args, **kwargs)
except exceptions as problem:
if delay is none:
report("function failed after retries. exceptions: ".format(func=function.__name__, num=len(delays), p=problems))
raise
else:
report("function fails of (). will retry in second(s)."\
.format(func=function.__name__, expt_name=type(problem).__name__, expt_msg=problem, delay=delay))
time.sleep(delay)
根據上面的**,會retry三次,每次間隔3,10,15秒。
@functools.wraps(function)的作用是使被裝飾的函式保留原有的函式名字和函式doc。
這個函式設計的很巧妙,比如 report=lambda *args: none
作者定義了"返回為none的函式"作為「report」引數的預設值。
Python隨心記 函式閉包為函式加上認證功能
函式閉包為函式加上認證功能def auth func func user name input 使用者名稱 strip user pass input 密 碼 strip if user name achun and user pass 77770000 ret func args,kwargs r...
Python 電腦上自動閱讀東方頭條
爸爸就愛看個這得兩毛錢 直接上 from pymouse import pymouse from pykeyboard import pykeyboard import time import random m pymouse k pykeyboard x,y m.position 獲取當前座標的位...
Go 語言為Fibonacci函式實現Read方法
go語言非常靈活,只要為物件實現了相應的方法就可以把他看成實現了某個介面,類似於durk type,為fibonacci實現read方法,就可以像讀取檔案一樣,去讀取下乙個fibonacci值。示例 ackage main import fmt io bufio strings strconv fu...