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

Python跨文件调用变量及模块函数无法运行问题排查

嘿,我看到你现在卡在corestart函数没法运行的问题上了,咱们一步步拆解问题、解决它:

最核心的原因:程序卡在无限循环里了

你看main.py的最后几行:

clear.clear()
start()
corestart(10)

start()函数里套了两层while True,是个无限循环,程序执行到start()就会一直停在命令输入的循环里,根本没机会走到下面的corestart(10)!这就是为啥这个函数完全没运行的原因。

怎么解决?用线程让两个循环同时跑

因为corestart也是个无限循环(要持续修改温度),不能和主命令循环串行执行,得让它在后台跑。我们可以用Python的threading模块来实现:

修改main.py的导入和最后执行逻辑:

# 先修正导入的语法错误(原来的一行写两个from是非法的)
from termcolor import colored
from time import sleep as wait
import clear
# 新增导入threading
import threading
from coretemp import ct, corestart

# ... 中间的start()函数代码保持不变 ...

cont = input("Press enter to continue> ")
clear.clear()

# 用后台线程启动corestart,daemon=True表示主线程结束时后台线程自动退出
threading.Thread(target=corestart, args=(10,), daemon=True).start()
# 再启动主命令循环
start()

顺便修复几个潜在的坑,避免后续出问题

  1. 温度判断逻辑混乱
    你main.py里temp命令的判断顺序有问题:

    elif ct < 4000:
        print( colored("Core temperature: " + str(ct) + "°C", "yellow"))
    elif ct >= 3000:
        print( colored("Core temperature: " + str(ct) + "°C", "red"))
    

    3000-3999的数值会先被ct <4000捕获,永远不会触发红色警告。调整顺序改成这样:

    elif cmd == "temp":
        if ct < 2000:
            print(colored(f"Core temperature: {ct}°C", "green"))
        elif ct < 3000:
            print(colored(f"Core temperature: {ct}°C", "yellow"))
        else:  # 大于等于3000就变红
            print(colored(f"Core temperature: {ct}°C", "red"))
    

    用f-string拼接字符串也比+更简洁安全。

  2. coolant模块的全局变量修改无效
    coolant.py里的coolact()函数修改coolactive时,没声明它是全局变量,导致修改的是局部变量,coretemp.py里的coolactive永远是False,温度只会上升不会下降:

    def coolact():
        global coolactive, coolam  # 必须声明要修改的全局变量
        print("Activating coolant...")
        wait(2)
        coolactive = True
        print(f"Coolant activated. {coolam} coolant remaining.")  # 用f-string避免类型错误
    
  3. coretemp模块的温度变化逻辑优化
    现在coretemp里的corestart会每秒打印温度,如果你不想在命令行里刷屏,可以把print(ct)去掉,只在用户输入temp命令时显示温度,体验会更好。

最后测试一下

修改完这些后,运行main.py,程序会先启动后台的温度变化线程,然后进入命令循环,输入temp就能看到温度在持续变化啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:06:47