python超时、继承、修饰

      **超时函数:**

   在编写程序的时候,往往会遇到跑一个程序半天没有结果,那我们改如何让他超时运行时自动停止呢?在网上找了相关资料有说通过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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章