使用 psutil 重置存储变量的值

Reset stored variable's value using 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")