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

使用from threading import *时出现NameError: name 'Thread' is not defined错误求助

解决线程代码的NameError及执行逻辑问题

问题根源

  1. NameError 原因:虽然你用了from threading import *,但在部分Python环境或PyCharm配置中,通配符导入可能无法正确加载Thread类。改用显式导入能彻底避免这类问题。
  2. 线程目标参数错误:你写的target=show()是直接调用了show函数,而不是传递函数对象。这会导致函数在创建线程时就立刻执行,线程启动后反而没有可运行的任务,同时也打乱了教程里预期的线程执行顺序。

修正后的可用代码

from threading import Thread

def show():
    print("This is a child thread")

# target传函数本身(不带括号),让线程启动后再执行函数
t = Thread(target=show)
t.start()

print("This is the parent thread")

关键说明

  • 显式导入Thread类,确保在任何环境下都能正确引用,直接解决NameError问题。
  • target=show传递的是函数对象,线程调用start()后才会执行show函数,这样就能得到和教程一致的线程执行效果(输出顺序可能因系统线程调度略有差异,但子线程的内容会正常执行)。

内容的提问来源于stack exchange,提问作者davy.jones

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:12:06