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

如何修复Python中的NameError?附出错代码寻求帮助

解决Python代码中的NameError问题

你的代码触发NameError的核心原因是缩进错误:两行打印CPU、内存使用情况的print语句没有包含在display_usage函数内部,导致它们无法访问函数定义的局部变量(cpu_bar、mem_bar、cpu_usage、mem_usage)。

修复后的代码

import time
import psutil

def display_usage(cpu_usage, mem_usage, bars=50):
    cpu_percent = (cpu_usage / 100.0)
    cpu_bar = '$' * int(cpu_percent*bars) + '-' * (bars - int(cpu_percent * bars))
    
    mem_percent = (mem_usage / 100.0)
    mem_bar= '$' * int(mem_percent * bars) + '-' * (bars - int(mem_percent * bars))

    # 将print语句缩进,放入函数内部
    print(f"\rCPU Usage: |{cpu_bar}| {cpu_usage:.2f}%  ", end="")
    print(f"MEM Usage: |{mem_bar}| {mem_usage:.2f}%  ", end="\r")

while True:
    display_usage(psutil.cpu_percent(), psutil.virtual_memory().percent, 30)
    time.sleep(0.5)

额外检查项

  • 确保已正确安装psutil库:在终端执行pip3 install psutil(M2 Mac通常需用pip3对应系统默认Python3)。
  • 确认VS Code中使用的Python解释器是安装了psutil的版本,可通过左下角的解释器选择器切换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 07:15:02