这是一个可停止线程的实现,并试图使用它:
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, target, kwargs):
super(StoppableThread, self).__init__(target, kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.it_set()
def func(s):
print(s)
t = StoppableThread(target = func, kwargs={"s":"Hi"})
t.start()
此代码生成错误:
Traceback (most recent call last):
File "test.py", line 19, in <module>
t = StoppableThread(target = func)
File "test.py", line 7, in __init__
super(StoppableThread, self).__init__(target)
File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 780, in __init__
assert group is None, "group argument must be None for now"
AssertionError: group argument must be None for now
我想知道为什么以及如何解决它。
答案 0 :(得分:1)
线程的第一个参数是group,因此你需要为target
命名super(StoppableThread, self).__init__(target=target, kwargs)
有文件
class threading.Thread(group = None,target = None,name = None,args =(), kwargs = {})
https://docs.python.org/2/library/threading.html#threading.Thread
答案 1 :(得分:0)
尝试以下方法:
import threading
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(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = Event()
*args
是一个包含每个位置参数的序列,**kwargs
是一个包含每个key-wrod参数的字典。通过使用此表示法,您将传递给StoppableThread
构造函数的每个参数传递给其父级。变量*args
和**kwargs
的名称是任意的。