Get process CPU usage in percentage in python

Viewed 245

I'm making an destktop application like task manager. How to get the specific cpu usage of google.exe?

2 Answers

You can use psutil library for your task

pip install psutil

Usage:

import psutil

chrome = None
for proc in psutil.process_iter():
    if proc.name() == "chrome.exe":
        chrome = proc
        print(chrome.cpu_percent())

You can use this code:

import psutil

for proc in psutil.process_iter():
    if proc.name() == 'chrome.exe':
        try:
            pinfo = proc.as_dict(attrs=['pid'])
        except psutil.NoSuchProcess:
            pass
        else:
            print(pinfo['pid'])
            p = psutil.Process(pinfo['pid'])
            print(p.cpu_percent(1))

But you should count sum of this process

Related