–
import subprocess
import re
def get_memory_usage():
# 执行 WMIC 命令并获取内存占用信息
可用物理内存_info = subprocess.check_output("wmic OS get FreePhysicalMemory", shell=True).decode()
总可见内存大小_info = subprocess.check_output("wmic OS get TotalVisibleMemorySize", shell=True).decode()
# 使用正则表达式提取 FreePhysicalMemory 和 TotalVisibleMemorySize 的值
free_memory = re.search(r'([0-9]+)', 可用物理内存_info).group(0)
total_memory = re.search(r'([0-9]+)', 总可见内存大小_info).group(0)
# 计算内存占用百分比
try:
memory_usage_percent_data = (1 - int(free_memory) / int(total_memory)) * 100
memory_usage_percent='{:.3f}'.format(memory_usage_percent_data)
return str(memory_usage_percent)+'%'
except ZeroDivisionError:
print("Error: Division by zero is not allowed.不允许除以零。")
return None # 或者可以设置为某个特定的错误代码或消息
–
发表回复