Skip to main content
 首页 » 编程设计

python之线程 : AssertionError: group argument must be None for now

2025年01月19日15lonelyxmas

这是一个可停止线程的实现和使用它的尝试:

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 

我想知道为什么以及如何修复它。

请您参考如下方法:

thread的第一个参数是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