简单记录一下利用python装饰器来调整函数的方法。现在有个需求:参数line范围为1-16,要求把9-16的范围转化为1-8,即9对应1,10对应2,...,16对应8。
下面是例子:
1 def format_lines(): 2 def make_wrapper(func): 3 def wrapper(*args, **kwargs): 4 lines = list(args)[1:] 5 new_args = list() 6 for index, line in enumerate(lines): 7 if isinstance(line,tuple): 8 for index, l in enumerate(line): 9 if line > 8 and line <16 : 10 line = line % 8 11 elif line == 16: 12 line = 8 13 new_args.insert(index,line) 14 new_args.insert(0,args[0]) 15 return func(*tuple(new_args), **kwargs) 16 else: 17 if line > 8 and line <16 : 18 line = line % 8 19 elif line == 16: 20 line = 8 21 new_args.insert(index,line) 22 new_args.insert(0,args[0]) 23 return func(*tuple(new_args), **kwargs) 24 return wrapper 25 return make_wrapper
注意:wrapper的参数args即实际的lines,修改完后,传递给实际的func函数即可
使用:
class MainCom_Usb_Cmd():
"""atc platform hardware usb cmd
"""
def __init__(self,ip,port):
self.address = (ip, int(port))
@format_lines()
def turn_on_usb_signal(self,*lines):
"""only turn on usb signal
"""
if not lines :
lines = range(1,9)
while True:
try:
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect(self.address)
break
except Exception, e:
time.sleep(0.1)
continue
try:
is_succeed = True
self.close_usb(lines,is_connect=True)
for line in lines:
retry_count = 0
while retry_count < 3:
self.client.send('SwitchToUSB:::&%d&&&&\n\r' % line)
time.sleep(.2)
data = self.client.recv(1024)
if len(data)>0:
print data
pattern = re.compile(r"CH%d\s+USB\s+sig\s+connect\s+to\s+PCUSB" % line)
match = pattern.search(data)
if match is None:
retry_count = retry_count + 1
else:
break
if retry_count >= 3:
is_succeed = False
except:
traceback.print_exc()
finally:
self.client.close()
return is_succeed
@format_lines()
def turn_on_usb_power(self,*lines):
"""only turn on usb power for fastly charging device
"""
if not lines:
lines = range(1,9)
while True:
try:
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect(self.address)
break
except Exception, e:
time.sleep(0.1)
continue
try:
is_succeed = True
self.close_usb(lines,is_connect=True)
for line in lines:
retry_count = 0
while retry_count < 3:
self.client.send('SwitchToDUT5V:::&%d&&&&\n\r' % line)
time.sleep(.2)
data = self.client.recv(1024)
if len(data)>0:
print data
pattern = re.compile(r"CH%d\s+USB\s+POWER\s+connect" % line)
match = pattern.search(data)
if match is None:
retry_count = retry_count + 1
else:
break
if retry_count >= 3:
is_succeed = False
except:
traceback.print_exc()
finally:
self.client.close()
return is_succeed