Windows服务器无第三方包获取CPU/RAM使用率报错求助
解决Windows环境下无第三方包获取CPU/RAM使用率的问题
错误原因分析
你之前的代码报错FileNotFoundError,核心问题是subprocess.run的第一个参数必须是可执行程序路径,而你直接把PowerShell命令作为第一个参数,系统会把它当成可执行文件去查找,自然找不到。正确的做法是调用powershell.exe,再将查询命令作为参数传递给它。
修正后的CPU使用率获取代码
import subprocess def get_cpu_usage(): # 调用PowerShell执行WMI查询,提取CPU使用率数值 cmd = [ 'powershell.exe', '-Command', 'Get-WmiObject -Class Win32_Processor | Select-Object -ExpandProperty LoadPercentage' ] # text=True 让输出以字符串返回,避免字节流处理 result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) if result.returncode != 0: raise Exception(f"获取CPU失败: {result.stderr.strip()}") # 多核心CPU会返回多个数值,取平均值 cpu_values = [int(val.strip()) for val in result.stdout.strip().split('\n') if val.strip()] return sum(cpu_values) / len(cpu_values) if cpu_values else 0.0 # 测试调用 print(f"当前CPU使用率: {get_cpu_usage()}%")
RAM使用率获取方案
方案1:PowerShell + WMI
import subprocess def get_ram_usage(): cmd = [ 'powershell.exe', '-Command', '$os = Get-WmiObject Win32_OperatingSystem; ' '$totalMem = $os.TotalVisibleMemorySize; ' '$freeMem = $os.FreePhysicalMemory; ' '([math]::Round((($totalMem - $freeMem)/$totalMem)*100, 2))' ] result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) if result.returncode != 0: raise Exception(f"获取内存失败: {result.stderr.strip()}") return float(result.stdout.strip()) # 测试调用 print(f"当前RAM使用率: {get_ram_usage()}%")
方案2:直接调用wmic命令(无需PowerShell)
如果系统禁用PowerShell,可改用wmic命令:
import subprocess def get_ram_usage(): # 获取总物理内存 total_cmd = ['wmic', 'os', 'get', 'TotalVisibleMemorySize', '/value'] total_result = subprocess.run(total_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) total_mem = int([line.split('=')[1].strip() for line in total_result.stdout.split('\n') if 'TotalVisibleMemorySize' in line][0]) # 获取空闲物理内存 free_cmd = ['wmic', 'os', 'get', 'FreePhysicalMemory', '/value'] free_result = subprocess.run(free_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) free_mem = int([line.split('=')[1].strip() for line in free_result.stdout.split('\n') if 'FreePhysicalMemory' in line][0]) # 计算使用率并保留两位小数 return round(((total_mem - free_mem) / total_mem) * 100, 2) # 测试调用 print(f"当前RAM使用率: {get_ram_usage()}%")
关键注意事项
- 确保Python进程有足够权限执行WMI/wmic命令(一般普通用户权限即可)
- 处理输出时要过滤空行,避免转换数值报错
- 捕获stderr输出,方便排查执行失败的原因
内容的提问来源于stack exchange,提问作者Elly
相关产品推荐
相关产品推荐

