我有这个要做:
import psutil
import read_config
mem = psutil.virtual_memory()
print('Total RAM: ', (round(mem[0] / (1024 * 1024))), '(MB)') # total
ram_usage = read_config.ram_usage
while ram_usage is True:
mem = psutil.virtual_memory()
print('Used RAM: ', (round(mem[3] / (1024 * 1024))), '(MB)', end="") # used
问题是,如果我执行,输出是这样的:
Total RAM: 3949 (MB)
Used RAM: 3069 (MB)Used RAM: 3069 (MB)Used RAM: 3069 (MB)Used RAM: 3069 (MB)Used RAM: 3069 (MB)
如何解决Used RAM
问题?我想在第二行打印使用的RAM的值,而不是每次满足条件时打印行。
由于
答案 0 :(得分:1)
要检测值是否已更改,只需保存旧值,然后有条件地打印:
old_mem = 0
while ram_usage is True:
mem = psutil.virtual_memory()
if mem[3] != old_mem:
old_mem = mem[3]
print('Used RAM: ', (round(mem[3] / (1024 * 1024))), '(MB)')
然而,这将检测到非常小的变化。如果您只想在显示的值发生变化时进行打印,请先转换为MB,然后比较:
old_mem = 0
while ram_usage is True:
mem = psutil.virtual_memory()
mem_mb = round(mem[3] / (1024 * 1024))
if mem_mb != old_mem:
old_mem = mem_mb
print('Used RAM: ', mem_mb, '(MB)')