我正在尝试使用an answer to another question提供的StoppableThread
类:
import threading
# Technique for creating a thread that can be stopped safely
# Posted by Bluebird75 on StackOverflow
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(StoppableThread, self).__init__()
self._stop = threading.Event()
def stop(self):
self._stop.set()
def stopped(self):
return self._stop.isSet()
但是,如果我运行类似:
st = StoppableThread(target=func)
我明白了:
TypeError:
__init__()
有一个意外的关键字参数'target'
可能是对如何使用它的疏忽。
答案 0 :(得分:5)
StoppableThread
类不会在构造函数中将threading.Thread
的任何其他参数传递或传递给它。你需要做这样的事情:
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self,*args,**kwargs):
super(threading.Thread,self).__init__(*args,**kwargs)
self._stop = threading.Event()
这会将位置和关键字参数传递给基类。
答案 1 :(得分:1)
您要覆盖 init , init 不会接受任何参数。你应该添加一个“target”参数并将它传递给你的基类构造函数,超级甚至更好地通过* args和* kwargs允许任意参数。
即
def __init__(self,*args,**kwargs):
super(threading.Thread,self).__init__(*args,**kwargs)
self._stop = threading.Event()