无法在 python 修饰中使用线程库获取函数的参数?

Can't get the parameters of a func using threading lib in a python decoration?

下面是python的代码,没有通过class继承自threading.thread创建的线程装饰就可以了。例如,通过将目标函数作为参数提供给 threading.thread()

创建一个线程
import threading ,time
from time import sleep, ctime
import functools

def find(func):
    @functools.wraps(func)
    def wrapper(*args,**kwargs):
        print("ags:%s,%s\n" % (args,kwargs))
        return func(*args, **kwargs)
    return wrapper

@find
def now() :
    return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )

class myThread (threading.Thread) :
    """docstring for myThread"""
    @find
    def __init__(self, nloop, nsec) :
        super(myThread, self).__init__()
        self.nloop = nloop
        self.nsec = nsec

    @find
    def run(self):
        print('start loop', self.nloop, 'at:', ctime())
        sleep(self.nsec)
        print('loop', self.nloop, 'done at:', ctime())
@find
def main():
    thpool=[]
    print('starting at:', now())

    for i in range(10):
        thpool.append(myThread(i,2))

    for th in thpool:
        th.start()

    for th in thpool:
        th.join()

    print('all Done at:', now())

if __name__ == '__main__':
    main()

我收到如下错误信息:

File "F:\question\multithreadfmclass.py", line 15, in wrapper
    print("ags:%s,%s\n" % (args,kwargs))
  File "D:\ProgramFiles\Python352\lib\threading.py", line 813, in __repr__
    assert self._initialized, "Thread.__init__() was not called"
AssertionError: Thread.__init__() was not called

如何消除错误?提前谢谢。

您在 Thread 对象初始化之前打印它,这是不可能的。由于你的装饰器,这个错误并不容易发现,但如果你先调用 func,那么它会起作用:

def find(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print("ags:%s,%s\n" % (args, kwargs))
        return result

return wrapper