如何解决在 Python 3.8 中获取进程的写入/读取字节和 CPU 使用率时出现问题
最近在我的学校期末考试项目中,我需要编写一个函数来返回进程的写入和读取字节以及 CPU 使用情况。我曾尝试使用 Psutil,尝试使用 WMI(找不到通过它接收写入和读取字节的方法),甚至尝试将它们组合起来。最后,尽管我每次在 Psutil 的几乎所有进程上都会收到访问被拒绝错误。希望得到一些帮助来解决这个问题。
编辑:使用 Windows 10
这是我目前拥有的代码:
import wmi
import psutil
from elevate import elevate
elevate()
c = wmi.WMI()
process_watcher = c.Win32_Process.watch_for("creation")
while True:
new_process = process_watcher()
pid = new_process.Processid
name = new_process.Caption
try:
curr_process = psutil.Process(pid=pid)
try:
# get the number of CPU cores that can execute this process
cores = len(curr_process.cpu_affinity())
except psutil.AccessDenied:
cores = 0
# get the CPU usage percentage
cpu_usage = curr_process.cpu_percent()
try:
# get the memory usage in bytes
memory_usage = curr_process.memory_full_info().uss
except psutil.AccessDenied:
memory_usage = 0
# total process read and written bytes
io_counters = curr_process.io_counters()
read_bytes = io_counters.read_bytes
write_bytes = io_counters.write_bytes
print(pid + ": " + name + ",Write bytes: " + write_bytes + ",cpu usage: "+ cpu_usage)
except:
print("Access Denied")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。