**超時函數:**
在編寫程序的時候,往往會遇到跑一個程序半天沒有結果,那我們改如何讓他超時運行時自動停止呢?在網上找了相關資料有說通過Singal實現的,但是在Windows似乎行不通,基於Thread的、timer的、timeout、timeout_decorator、都無法實現超時結束程序,可能是因爲版本的緣故吧,我用的是python3.6版本。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
import threading
import time
import inspect
import ctypes
def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("PyThreadState_SetAsyncExc failed")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
def mytimeout(ctime):
"""
修飾函數之超時函數
:param ctime:超時時間
:return:
"""
ctime=ctime
def timeout(func):
def call():
t=threading.Thread(target=func)
t.setDaemon(True)
t.start()
t.join(ctime)
print("超時!")
return call
return timeout
@mytimeout(5)
def mytest():
time.sleep(10)
print("I Love You!")
mytest()
代碼裏面的mytimeout就是超時函數,可以對函數進行超時限制,可以通過更改時間來判斷是否進行了超時結束程序。通過python中的多線程threading線程守護實現。如果只打印了超時說明當前線程提前中斷了,如果打印了兩個說明運行正常,可以根據自己的實際情況在此基礎上進行修改運用。stop_thread可以用來結束某一個線程。
修飾函數可以參考:https://www.cnblogs.com/gregoryli/p/7819341.html
在實際中如果要控制一個函數超時的話建議使用Thread來進行控制更直接。
class SetRTCThread(QThread):
def __init__(self,ser,maxtime=5,parent=None):
super(SetRTCThread, self).__init__(parent)
self.ser=ser
self.maxtime=maxtime
def run(self):
t1 = threading.Thread(target=Set_Serial, args=(self.ser,))
t1.setDaemon(True)
t1.start()
t1.join(self.maxtime)
#這是一個控制串口操作的例子,在init中輸入串口和超時時間默認5s,在run中輸入線程控制函數Set_Serial,和其相關參數.
"""
使用的時候直接在需要調用的地方調用就行
"""
# SetRTCThread(ser,maxtime).run()#輸入相應控制參數
**繼承:**
通過繼承原有函數的方式實現新寫的函數同時具備全部功能。
1.經典類的寫法: 父類名稱.__init__(self,參數1,參數2,...)
2. 新式類的寫法:super(子類,self).__init__(參數1,參數2,....)
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
class Parent(object):
def __init__(self,name):
self.name=name
def ShowParent(self):
print("父親的姓名:{0}".format(self.name))
class Son(Parent):
def __init__(self,parent,son,sonage):
Parent.__init__(self,parent)#經典類
# super(Son, self).__init__(parent)#新式類
self.son=son
self.sonage=sonage
def ShowSon(self):
print("兒子的姓名:{0}年齡:{0}".format(self.son,self.sonage))
tmp=Son("張三",'張文',20)
tmp.ShowParent()
tmp.ShowSon()
**修飾:**
修飾函數通過在定義的函數前面添加@修飾函數來實現相應的功能,在前面的超時函數中有出現,在此給出一個簡單的示例,通過修飾函數計算一個函數的運行時間。修飾可以理解爲給程序打補丁。
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
import time
def timeslong(func):
def call():
start = time.clock()
# start=time.time()#兩種計算時間的方式
func()
end = time.clock()
print("Run Time:%s." % (end - start))
# return "It's used : %s ." % (end - start)
return call
@timeslong
def Test():
y = 0
for i in range(10):
y = y + i + 1
print(y)
return y
Test()
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# author:SingWeek
""""""
"""函數裝飾函數"""
def wrapFun(func):
def inner(a, b):
print('function name:', func.__name__)
r = func(a, b)
print('function',r)
return r
return inner
@wrapFun
def myadd(a, b):
return a + b
print(myadd(2, 3))
"""函數裝飾類,可以通過修飾函數來限制參數輸入個數是否正確"""
def wrapClass(cls):
def inner(a,b):
print('class name:', cls.__name__)
return cls(a,b)
return inner
@wrapClass
class Foo():
def __init__(self, a,b):
self.a = a
def fun(self):
print('self.a =', self.a)
m = Foo('xiemanR',1)
m.fun()
"""類裝飾函數"""
class ShowFunName():
def __init__(self, func):
self._func = func
def __call__(self, a):
print('function name:', self._func.__name__)
a=a+'我來了'
return self._func(a)
@ShowFunName
def Bar(a):
return a
print(Bar('xiemanR'))
"""類裝飾類"""
class ShowClassName(object):
def __init__(self, cls):
self._cls = cls
def __call__(self, a):
print('class name:', self._cls.__name__)
return self._cls(a)
@ShowClassName
class Foobar(object):
def __init__(self, a):
self.value = a
def fun(self):
print(self.value)
a = Foobar('xiemanR')
a.fun()