自定义Python Thread类触发assert group is None错误的原因及解决办法
问题原因
你触发的assert group is None错误,根源在自定义VerseThread类的__init__方法里:
super().__init__(self, args=args)
Python中使用super()调用父类构造方法时,不需要显式传递self参数——super()会自动绑定当前实例。你这里把self当成了父类threading.Thread.__init__的第一个参数(也就是group参数)传入,而Python线程模块目前要求group必须为None,直接触发了断言检查。
另外你的代码还有一个潜在问题:run方法里用到了self.parser,但__init__中没有初始化这个属性,运行时会抛出AttributeError。
解决方案
- 修正父类构造方法的调用,移除多余的
self参数 - 在
VerseThread的__init__中添加parser参数并初始化,确保run方法能正常调用self.parser.parse
修正后的完整代码
自定义VerseThread类
class VerseThread(threading.Thread): def __init__(self, args, parser): # 移除多余的self参数,正确调用父类构造 super().__init__(args=args) self.parser = parser # 初始化parser属性 def run(self): self.exc = None try: book, abbrev, template, chapter = self.args self.parser.parse(book, abbrev, template, chapter) except ChapterNotFoundError as e: self.exc = e def join(self): threading.Thread.join(self) if self.exc: raise self.exc
线程创建与运行代码
for book, abbrev, testament in self.books[init:end]: base_chapter = 1 while True: threads = [] if testament == 'ot': for i in range(3): # 传入当前实例的parser给VerseThread threads.append(VerseThread( args=(book, abbrev, OT_TEMPLATE, base_chapter+i), parser=self.parser )) else: for i in range(3): threads.append(VerseThread( args=(book, abbrev, NT_TEMPLATE, base_chapter+i), parser=self.parser )) try: for thread in threads: thread.start() # 直接启动,无需判断is_alive(刚创建的线程必然未启动) for thread in threads: thread.join() base_chapter += 3 except ChapterNotFoundError as e: LOGGER.info(f"{{PROCESS {multiprocessing.current_process().pid}}} - Chapter {e.chapter} not found in {book}, exiting book...") break
额外说明
- 原代码中
if not thread.is_alive(): thread.start()是多余的:刚创建的Thread实例默认处于未启动状态,直接调用start()即可。 - 使用
thread.run()能正常执行是因为它只是在当前线程同步调用run方法,不会触发线程创建流程中的group参数检查,但这样就失去了多线程的意义。
内容的提问来源于stack exchange,提问作者arthurIsVibing
相关产品推荐
相关产品推荐

