Last active
September 16, 2015 03:41
-
-
Save ficapy/929926b7b9fad8ffb33f to your computer and use it in GitHub Desktop.
将装饰器改成with语句,使用with语句实现错误重试
This file contains 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
import random | |
from tt import retrys | |
def g(): | |
pass | |
class A(): | |
def __init__(self): | |
self.a = 0 | |
self.b = 2 | |
@classmethod | |
def e(cls): | |
pass | |
@staticmethod | |
def f(): | |
pass | |
def c(self, d): | |
with retrys(): | |
if random.random() > 0.5: | |
raise Exception('dd') | |
print('success', self, d, self.e, self.f, g) | |
b = A() | |
b.c(2) |
This file contains 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
# -*- coding: utf-8 -*- | |
from contextlib import contextmanager | |
@contextmanager | |
def retrys(max_tries=4): | |
import codecs | |
import re | |
import time | |
import math | |
import traceback | |
from inspect import getouterframes, currentframe, getmembers | |
index = list(map(lambda item: item[-2][0].strip().startswith('with'), getouterframes(currentframe()))).index(True) | |
(frame, filename, line_number, | |
function_name, lines, index) = getouterframes(currentframe())[index] | |
member = getmembers(frame) | |
f_locals_index = ['f_locals' in i for i in member].index(True) | |
f_globals_index = ['f_globals' in i for i in member].index(True) | |
params = {} | |
params.update(member[f_locals_index][-1]) | |
params.update(member[f_globals_index][-1]) | |
# 仅仅适用于python2 | |
for key, value in params.items(): | |
exec ('{}=value'.format(key)) | |
try: | |
yield | |
except: | |
time.sleep(1) | |
for i in range(1, max_tries): | |
with codecs.open(filename, 'r', 'utf-8') as f: | |
text = f.readlines() | |
flag = re.findall('^\s+', ' ' + text[line_number])[0].__len__() | |
content = '' | |
for line in text[line_number:]: | |
blank = re.findall('^\s+', ' ' + line)[0].__len__() | |
if blank < flag: | |
break | |
content += line[flag - 1:] | |
try: | |
exec (content) | |
except: | |
print('================================================') | |
traceback.print_exc() | |
if i != max_tries - 1: | |
time.sleep(math.pow(2, i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment