Python psutil запущенные процессы

psutil 5.9.5

Cross-platform lib for process and system monitoring in Python.

Ссылки проекта

Статистика

Метаданные

Лицензия: BSD License (BSD-3-Clause)

Метки ps, top, kill, free, lsof, netstat, nice, tty, ionice, uptime, taskmgr, process, df, iotop, iostat, ifconfig, taskset, who, pidof, pmap, smem, pstree, monitoring, ulimit, prlimit, smem, performance, metrics, agent, observability

Требует: Python >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*

Сопровождающие

Классификаторы

  • Development Status
    • 5 — Production/Stable
    • Console
    • Win32 (MS Windows)
    • Developers
    • Information Technology
    • System Administrators
    • OSI Approved :: BSD License
    • MacOS :: MacOS X
    • Microsoft
    • Microsoft :: Windows :: Windows 7
    • Microsoft :: Windows :: Windows 8
    • Microsoft :: Windows :: Windows 8.1
    • Microsoft :: Windows :: Windows 10
    • Microsoft :: Windows :: Windows Server 2003
    • Microsoft :: Windows :: Windows Server 2008
    • Microsoft :: Windows :: Windows Vista
    • OS Independent
    • POSIX
    • POSIX :: AIX
    • POSIX :: BSD
    • POSIX :: BSD :: FreeBSD
    • POSIX :: BSD :: NetBSD
    • POSIX :: BSD :: OpenBSD
    • POSIX :: Linux
    • POSIX :: SunOS/Solaris
    • C
    • Python
    • Python :: 2
    • Python :: 2.7
    • Python :: 3
    • Python :: Implementation :: CPython
    • Python :: Implementation :: PyPy
    • Software Development :: Libraries
    • Software Development :: Libraries :: Python Modules
    • System :: Benchmark
    • System :: Hardware
    • System :: Hardware :: Hardware Drivers
    • System :: Monitoring
    • System :: Networking
    • System :: Networking :: Monitoring
    • System :: Networking :: Monitoring :: Hardware Watchdog
    • System :: Operating System
    • System :: Systems Administration
    • Utilities

    Описание проекта

    Summary

    psutil (process and system utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. It is useful mainly for system monitoring, profiling and limiting process resources and management of running processes. It implements many functionalities offered by classic UNIX command line tools such as ps, top, iotop, lsof, netstat, ifconfig, free and others. psutil currently supports the following platforms:

    Supported Python versions are 2.7, 3.4+ and PyPy.

    Funding

    While psutil is free software and will always be, the project would benefit immensely from some funding. Keeping up with bug reports and maintenance has become hardly sustainable for me alone in terms of time. If you’re a company that’s making significant use of psutil you can consider becoming a sponsor via GitHub Sponsors, Open Collective or PayPal and have your logo displayed in here and psutil doc.

    Sponsors

    Example usages

    This represents pretty much the whole psutil API.

    Источник

    Python : Check if a process is running by name and find it’s Process ID (PID)

    In this article we will discuss a cross platform way to find a running process PIDs by name using psutil.

    To install python’s psutil library use,

    Check if a process is running

    To check if process is running or not, let’s iterate over all the running process using psutil.process_iter() and match the process name i.e.

    import psutil def checkIfProcessRunning(processName): ''' Check if there is any running process that contains the given name processName. ''' #Iterate over the all the running process for proc in psutil.process_iter(): try: # Check if process name contains the given name string. if processName.lower() in proc.name().lower(): return True except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass return False;

    Let’s use this function to check if any process with ‘chrome’ substring in name is running or not i.e.

    Frequently Asked:

    # Check if any chrome process was running or not. if checkIfProcessRunning('chrome'): print('Yes a chrome process was running') else: print('No chrome process was running')
    Yes a chrome process was running

    As in my system many chrome instances are running. So it will return True. But how to get the process ID of all the running ‘chrome.exe’ process ?

    Find PID (Process ID) of a running process by Name

    As there may be many running instances of a given process. So, we will iterate over all the running process and for each process whose name contains the given string, we will keep it’s info in a list i.e.

    import psutil def findProcessIdByName(processName): ''' Get a list of all the PIDs of a all the running process whose name contains the given string processName ''' listOfProcessObjects = [] #Iterate over the all the running process for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time']) # Check if process name contains the given name string. if processName.lower() in pinfo['name'].lower() : listOfProcessObjects.append(pinfo) except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) : pass return listOfProcessObjects;

    Let’s call this function to get the PIDs of all the running chrome.exe process

    # Find PIDs od all the running instances of process that contains 'chrome' in it's name listOfProcessIds = findProcessIdByName('chrome') if len(listOfProcessIds) > 0: print('Process Exists | PID and other details are') for elem in listOfProcessIds: processID = elem['pid'] processName = elem['name'] processCreationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time'])) print((processID ,processName,processCreationTime )) else : print('No Running Process found with given text')

    Contents of the list will be,

    (2604, 'chrome.exe', '2018-11-10 19:12:13') (4276, 'chrome.exe', '2018-11-10 19:12:14') (9136, 'chrome.exe', '2018-11-10 19:12:14') (9616, 'chrome.exe', '2018-11-10 19:43:41') (12904, 'chrome.exe', '2018-11-10 19:12:13') (13476, 'chrome.exe', '2018-11-10 20:03:04') (15520, 'chrome.exe', '2018-11-10 20:02:22')

    We can do the same in a single line using list comprehension i.e.

    # Find PIDs od all the running instances of process that contains 'chrome' in it's name procObjList = [procObj for procObj in psutil.process_iter() if 'chrome' in procObj.name().lower() ]

    procObjList is a list of Process class objects. Let’s iterate over it and print them i.e.

    for elem in procObjList: print (elem)
    psutil.Process(pid=2604, name='chrome.exe', started='19:12:13') psutil.Process(pid=4276, name='chrome.exe', started='19:12:14') psutil.Process(pid=9136, name='chrome.exe', started='19:12:14') psutil.Process(pid=9616, name='chrome.exe', started='19:43:41') psutil.Process(pid=12904, name='chrome.exe', started='19:12:13') psutil.Process(pid=13476, name='chrome.exe', started='20:03:04') psutil.Process(pid=15520, name='chrome.exe', started='20:02:22')

    Complete example is as follows,

    import psutil import time def checkIfProcessRunning(processName): ''' Check if there is any running process that contains the given name processName. ''' #Iterate over the all the running process for proc in psutil.process_iter(): try: # Check if process name contains the given name string. if processName.lower() in proc.name().lower(): return True except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass return False; def findProcessIdByName(processName): ''' Get a list of all the PIDs of a all the running process whose name contains the given string processName ''' listOfProcessObjects = [] #Iterate over the all the running process for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time']) # Check if process name contains the given name string. if processName.lower() in pinfo['name'].lower() : listOfProcessObjects.append(pinfo) except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) : pass return listOfProcessObjects; def main(): print("*** Check if a process is running or not ***") # Check if any chrome process was running or not. if checkIfProcessRunning('chrome'): print('Yes a chrome process was running') else: print('No chrome process was running') print("*** Find PIDs of a running process by Name ***") # Find PIDs od all the running instances of process that contains 'chrome' in it's name listOfProcessIds = findProcessIdByName('chrome') if len(listOfProcessIds) > 0: print('Process Exists | PID and other details are') for elem in listOfProcessIds: processID = elem['pid'] processName = elem['name'] processCreationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time'])) print((processID ,processName,processCreationTime )) else : print('No Running Process found with given text') print('** Find running process by name using List comprehension **') # Find PIDs od all the running instances of process that contains 'chrome' in it's name procObjList = [procObj for procObj in psutil.process_iter() if 'chrome' in procObj.name().lower() ] for elem in procObjList: print (elem) if __name__ == '__main__': main()
    *** Check if a process is running or not *** Yes a chrome process was running *** Find PIDs of a running process by Name *** Process Exists | PID and other details are (2604, 'chrome.exe', '2018-11-10 19:12:13') (4276, 'chrome.exe', '2018-11-10 19:12:14') (9136, 'chrome.exe', '2018-11-10 19:12:14') (9616, 'chrome.exe', '2018-11-10 19:43:41') (12904, 'chrome.exe', '2018-11-10 19:12:13') (13476, 'chrome.exe', '2018-11-10 20:03:04') (15520, 'chrome.exe', '2018-11-10 20:02:22') ** Find running process by name using List comprehension ** psutil.Process(pid=2604, name='chrome.exe', started='19:12:13') psutil.Process(pid=4276, name='chrome.exe', started='19:12:14') psutil.Process(pid=9136, name='chrome.exe', started='19:12:14') psutil.Process(pid=9616, name='chrome.exe', started='19:43:41') psutil.Process(pid=12904, name='chrome.exe', started='19:12:13') psutil.Process(pid=13476, name='chrome.exe', started='20:03:04') psutil.Process(pid=15520, name='chrome.exe', started='20:02:22')

    Источник

    Читайте также:  Div с горизонтальной прокруткой css
Оцените статью