[英]Get usage disk of a Windows process by name in Python
I would like to create a script that wait until a specific process has 0 MB/s of disk usage.我想创建一个脚本,等待特定进程的磁盘使用率为 0 MB/s。
import time
import psutil
def get_process(name):
process = None
for p in psutil.process_iter():
if name in p.as_dict()["name"].lower():
process = p
return process
def wait_process(name):
process = get_process(name)
if process:
while process.disk_usage() > 0:
time.sleep(5)
wait_process("firefox")
I tried the psutil module but it seems we can't get disk usage by process.我尝试了 psutil 模块,但似乎我们无法按进程获取磁盘使用情况。
EDIT编辑
I tried this but I get irrelevant number.我试过这个,但我得到了不相关的数字。
def process_disk_usage(process_name: str) -> float:
# process = None
for p in psutil.process_iter():
if process_name.lower() in p.as_dict()["name"].lower():
r_bytes = p.io_counters()[2]
w_bytes = p.io_counters()[3]
t_bytes = r_bytes + w_bytes
return t_bytes / (1024.0 * 1024.0)
return None
def wait_process(process_name: str) -> None:
while process_disk_usage(process_name) > 0:
time.sleep(5)
p = psutil.Process()
io_counters = p.io_counters()
disk_usage_process = io_counters[2] + io_counters[3] # read_bytes + write_bytes
disk_io_counter = psutil.disk_io_counters()
disk_total = disk_io_counter[2] + disk_io_counter[3] # read_bytes + write_bytes
print("Disk", disk_usage_process/disk_total * 100)
Answered here: How to get current disk IO and network IO into percentage using Python?在这里回答: 如何使用 Python 将当前磁盘 IO 和网络 IO 设为百分比?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.