You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python threading模块RLock属性报错(疑似循环导入)求助

解决threading模块循环导入导致的AttributeError问题

问题详情

我是Python新手,正在做个人项目。主文件夹内仅有setup_log.txt和setup_tool.py两个文件,我写了一个使用threading模块的Spinner类:

import threading
class Spinner:
    def __init__(self, message="Processing"):
        self.spinner = itertools.cycle(['|', '/', '-', '\\'])
        self.stop_running = threading.Event()
        self.message = message
        self.thread = threading.Thread(target=self.init_spin)

    def init_spin(self):
        while not self.stop_running.is_set():
            sys.stdout.write(f'\r{self.message} {next(self.spinner)}')
            sys.stdout.flush()
            time.sleep(0.1)
        sys.stdout.write('\r' + ' ' * len(self.message) + ' \r')  # Clear the line

    def start(self):
        self.thread.start()

    def stop(self):
        self.stop_running.set()
        self.thread.join()

运行python setup_tools.py时触发以下错误:

Traceback (most recent call last):
File "C:\Users\XXXXXXX\Desktop\2024\asc_developer_V2\setup_tool.py", line 2, in
import subprocess
File "C:\Users\XXXXXXX\AppData\Local\Programs\Python\Python312\Lib\subprocess.py", line 51, in
import threading
File "C:\Users\XXXXXXX\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 3, in
import logging
File "C:\Users\XXXXXXX\AppData\Local\Programs\Python\Python312\Lib\logging_init_.py", line 232, in
_lock = threading.RLock()
^^^^^^^^^^^^^^^
AttributeError: partially initialized module 'threading' has no attribute 'RLock' (most likely due to a circular import)

解决方案

1. 排查文件命名冲突

这是循环导入错误的最常见原因:检查当前目录及上级目录中,是否存在和标准库模块同名的文件(比如threading.py、logging.py),如果有,立即重命名这类文件——Python会优先加载当前目录下的同名文件,导致标准库模块无法正常初始化。

2. 调整导入顺序

将标准库模块的导入放在自定义代码之前,避免先加载自定义代码时提前导入threading,干扰后续标准库的导入流程。修改setup_tool.py的导入顺序:

# 先导入所有标准库模块
import subprocess
import threading
import itertools
import sys
import time

# 再定义自定义Spinner类
class Spinner:
    def __init__(self, message="Processing"):
        self.spinner = itertools.cycle(['|', '/', '-', '\\'])
        self.stop_running = threading.Event()
        self.message = message
        self.thread = threading.Thread(target=self.init_spin)

    def init_spin(self):
        while not self.stop_running.is_set():
            sys.stdout.write(f'\r{self.message} {next(self.spinner)}')
            sys.stdout.flush()
            time.sleep(0.1)
        sys.stdout.write('\r' + ' ' * len(self.message) + ' \r')  # Clear the line

    def start(self):
        self.thread.start()

    def stop(self):
        self.stop_running.set()
        self.thread.join()

3. 补充缺失的导入

你的Spinner类代码里缺少itertools、sys、time三个模块的导入,必须补充,否则会触发NameError。

4. 修复Python环境(可选)

如果上述方法无效,可能是Python标准库文件损坏,尝试重新安装对应版本的Python,恢复干净的标准库环境。

内容的提问来源于stack exchange,提问作者PFlorentino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 23:32:07