使用 psutil 重置存储变量的值

问题描述

问候

我正在尝试使用 psutil 查找我的 Python 脚本有多少 cpu/RAM。我做了一些简单的循环来使用 psutil.cpu_percent 打印 cpu 使用率的值,但唯一打印的是第一个值。

有没有办法,也许可以在打印后重置​​变量值?因为当我使用 top 从中查看 cpu 使用量时,结果是不同的。

谢谢

循环脚本

import psutil
import time

p = psutil.Process(1594) #1594 is the PID of the script I want to observe
cpu_status = p.cpu_percent(interval=1)
n = 0

try:
        while n != 10:
                print(cpu_status)
                n = n + 1
                time.sleep(1)

except KeyboardInterrupt:
        print("quit")

结果

87.9
87.9
87.9
87.9
87.9
87.9
87.9
87.9
87.9
87.9

我期待的结果是这样的

87.9
89.0
88.1
70.2
80.4
87.9
89.0
88.1
70.2
80.4

解决方法

找到了。 它只是简单地将变量放入循环中。抱歉打扰你了,我要好好学习一下。

之前

p = psutil.Process(1594) #1594 is the PID of the script I want to observe
cpu_status = p.cpu_percent(interval=1)
n = 0

try:
        while n != 10:
                print(cpu_status)
                n = n + 1
                time.sleep(1)

except KeyboardInterrupt:
        print("quit")

修复后

p = psutil.Process(1594) #1594 is the PID of the script I want to observe
n = 0

try:
        while n != 10:
                print(p.cpu_percent(interval=1))
                n = n + 1
                time.sleep(1)

except KeyboardInterrupt:
        print("quit")