- how do I get the process list in Python?
- 4 Answers 4
- Not the answer you’re looking for? Browse other questions tagged python unix kill ps processlist or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Python : Get List of all running processes and sort by highest memory usage
- How to install psutil python library
- Create a list of all running process by Iterating over them
- Get List of all running process sorted by Highest Memory Usage
- How to Find and List All Running Processes with Python
- The Cross-Platform Solution!
- topin89 / get_processes_dlls_threads.py
how do I get the process list in Python?
How do I get a process list of all running processes from Python, on Unix, containing then name of the command/process and process id, so I can filter and kill processes.
4 Answers 4
On linux, the easiest solution is probably to use the external ps command:
On other systems you might have to change the options to ps .
Still, you might want to run man on pgrep and pkill .
The right portable solution in Python is using psutil. You have different APIs to interact with PIDs:
. and if you want to «search and kill»:
On Linux, with a suitably recent Python which includes the subprocess module:
You may need to tweak the ps command slightly depending on your exact needs.
Why Python?
You can directly use killall on the process name.
Not the answer you’re looking for? Browse other questions tagged python unix kill ps processlist or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Python : Get List of all running processes and sort by highest memory usage
In this article we will discuss a cross platform way to get a list of all running processes in system and then sort them by memory usage.
Python provides a cross platform library psutil to fetch sunning system details like process and system details.
How to install psutil python library
To install psutil using pip execute following command,
It will install the psutil. To use that in code import the module i.e.
Create a list of all running process by Iterating over them
psutil provides a function to iterate over all the running process i.e.
It will yield an Process class Iterator for all running processes and we can fetch other details from that Process object iterator.
For example, let’s iterate over all the running process and fetch Process Name and Process ID i.e.
Output will be like,
Output will vary system to system based on current running process.
Each process object yielded by process_iter() has information about that running process like, id , name, user name, parent id, memory usage and cpu usage etc.
Process object also provides a function to get the process detail as dictionary,
It will return the value of process attribute passed as dict i.e.
Let’s use this function on process object of each running process and generate list of dictionaries i,e,
Contents of list listOfProcessNames are as follows,
We can pass other important attributes too in as_dict() like,
Check library documentation for more attributes.
Get List of all running process sorted by Highest Memory Usage
It will iterate over the list of all running process and fetch memory usage along with id and name as dict.
Process class provides the memory info of process, it fetches the virtual memory usage from it, then appends the dict for each process to a list. In the end sort the list of dictionary by key vms, so list of process will be sorted by memory usage.
Let’s call this function and print top 5 process by memory usage i.e.
Complete code is as follows,
How to Find and List All Running Processes with Python
The other day, I was tasked with finding a way to get a list of all running processes on a Windows XP virtual machine. I was also supposed to include information about how much CPU and memory each process used. Fortunately, this didn’t have to be a remote script, but one that could be run on the client. After a fair bit of Googling here and there, I finally found a solution. In this article, we’ll look at some of the rejects as well as the eventual solution, which happens to work cross-platform.
One of the first scripts I found was this one back from March of 2006:
This script requires the PyWin32 package to work. However, while it’s a handy little script, it doesn’t show anything that I want except the ProcessId. I don’t really care about the user or kernel mode times (i.e. the total CPU time by user or kernel). Also I don’t really like working with the black magic of COM, so I ended up rejecting this one out of hand.
Next up was an ActiveState recipe. It looked promising:
Alas, while this also got me a list of processes from my Windows box (along with the PID), it didn’t give me any information on the CPU and memory utilization. I think this one could work if I used different counter names. I’m guessing if you wanted, you could figure out that information using MSDN. I didn’t want to mess with that, so I continued digging.
That recipe led me to the following one based on ctypes:
This is pretty clever looking, but I’m pretty bad at parsing ctypes. It’s something I want to learn, but I had a deadline, doggone it! Plus this one only showed a list of running processes but no information about them. Fortunately, the author included a reference, but I decided to keep looking.
Next I found a thread about using Tim Golden’s handy WMI module to do this sort of thing (below is copied right from the thread):
This is some cool stuff and I use Golden’s modules in some of my other code. However, I was still uncertain as to which counters to use to get to my information. I thought most of this stuff would just be coded for me or something! Well, it turned out that there is a package out there that does exactly what I needed AND it works on all the three of the major platforms! Amazing!
The Cross-Platform Solution!
The package’s name is psutil and it was what I decided to use. Here’s what I ended up with:
Yes, it’s an infinite loop and yes, that’s usually a very bad thing to do (except in GUI programming). However, for my purpose, I needed a way to check the user’s processes every 5 minutes or so to see what was causing the machine to act so weird. Thus, the script needs to run forever and log the results to uniquely named files. That’s all this script does, along with a little formatting magic. Feel free to use it or not as you see fit.
I hope you found this collection of material helpful. Hopefully it will save you all the digging I went through!
Note: While this last script appears to work just fine on Windows XP, on Windows 7 32 and 64-bit, you will get an “Access Denied” traceback, I suspect this is caused by Window 7’s increased security, but I will try to find a workaround.
UPDATE (10/09/2010) – The psutil folks don’t know why it doesn’t work, but one of their developers has confirmed the issue. You can follow along on their Google Groups list.
topin89 / get_processes_dlls_threads.py
#Based on recipe http://code.activestate.com/recipes/576362-list-system-process-and-process-information-on-win/ |
#also hosted here https://github.com/ActiveState/code/blob/master/recipes/Python/576362_List_System_Process_Process/recipe-576362.py |
#by winterTTr Dong , http://code.activestate.com/recipes/users/4164498/ |
#updated by topin89 |
#License: MIT |
from ctypes import c_long , c_int , c_uint , c_char , c_ubyte , c_char_p , c_void_p , c_size_t , c_ulong , c_wchar |
from ctypes import windll |
from ctypes import Structure |
from ctypes import sizeof , POINTER , pointer , cast |
# const variable |
TH32CS_SNAPPROCESS = 2 |
TH32CS_SNAPMODULE = 0x00000008 |
TH32CS_SNAPTHREAD = 0x00000004 |
STANDARD_RIGHTS_REQUIRED = 0x000F0000 |
SYNCHRONIZE = 0x00100000 |
PROCESS_ALL_ACCESS = ( STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF ) |
MAX_PATH = 260 |
MAX_MODULE_NAME32 = 255 |
# originally just PROCESSENTRY32 |
class PROCESSENTRY32A ( Structure ): |
_fields_ = [ ( ‘dwSize’ , c_ulong ) , |
( ‘cntUsage’ , c_ulong ) , |
( ‘th32ProcessID’ , c_ulong ) , |
( ‘th32DefaultHeapID’ , c_size_t ) , |
( ‘th32ModuleID’ , c_ulong ) , |
( ‘cntThreads’ , c_ulong ) , |
( ‘th32ParentProcessID’ , c_ulong ) , |
( ‘pcPriClassBase’ , c_long ) , |
( ‘dwFlags’ , c_ulong ) , |
( ‘szExeFile’ , c_char * MAX_PATH ) ] |
# c_wchar instead of c_char is the only difference |
class PROCESSENTRY32W ( Structure ): |
_fields_ = [ ( ‘dwSize’ , c_ulong ) , |
( ‘cntUsage’ , c_ulong ) , |
( ‘th32ProcessID’ , c_ulong ) , |
( ‘th32DefaultHeapID’ , c_size_t ) , |
( ‘th32ModuleID’ , c_ulong ) , |
( ‘cntThreads’ , c_ulong ) , |
( ‘th32ParentProcessID’ , c_ulong ) , |
( ‘pcPriClassBase’ , c_long ) , |
( ‘dwFlags’ , c_ulong ) , |
( ‘szExeFile’ , c_wchar * MAX_PATH ) ] |
# originally just MODULEENTRY32 |
class MODULEENTRY32A ( Structure ): |
_fields_ = [ ( ‘dwSize’ , c_ulong ) , |
( ‘th32ModuleID’ , c_ulong ), |
( ‘th32ProcessID’ , c_ulong ), |
( ‘GlblcntUsage’ , c_ulong ), |
( ‘ProccntUsage’ , c_ulong ) , |
( ‘modBaseAddr’ , c_size_t ) , #POINTER(c_ubyte) in MSDN |
( ‘modBaseSize’ , c_ulong ) , |
( ‘hModule’ , c_void_p ) , |
( ‘szModule’ , c_char * ( MAX_MODULE_NAME32 + 1 ) ), |
( ‘szExePath’ , c_char * MAX_PATH ) ] |
# c_wchar instead of c_char is the only difference |
class MODULEENTRY32W ( Structure ): |
_fields_ = [ ( ‘dwSize’ , c_ulong ) , |
( ‘th32ModuleID’ , c_ulong ), |
( ‘th32ProcessID’ , c_ulong ), |
( ‘GlblcntUsage’ , c_ulong ), |
( ‘ProccntUsage’ , c_ulong ) , |
( ‘modBaseAddr’ , c_size_t ) , #POINTER(c_ubyte) in MSDN |
( ‘modBaseSize’ , c_ulong ) , |
( ‘hModule’ , c_void_p ) , |
( ‘szModule’ , c_wchar * ( MAX_MODULE_NAME32 + 1 ) ), |
( ‘szExePath’ , c_wchar * MAX_PATH ) ] |
class THREADENTRY32 ( Structure ): |
_fields_ = [ |
( ‘dwSize’ , c_long ), |
( ‘cntUsage’ , c_long ), |
( ‘th32ThreadID’ , c_long ), |
( ‘th32OwnerProcessID’ , c_long ), |
( ‘tpBasePri’ , c_long ), |
( ‘tpDeltaPri’ , c_long ), |
( ‘dwFlags’ , c_long ) ] |
# forigen function |
## CreateToolhelp32Snapshot |
CreateToolhelp32Snapshot = windll . kernel32 . CreateToolhelp32Snapshot |
CreateToolhelp32Snapshot . reltype = c_long |
CreateToolhelp32Snapshot . argtypes = [ c_ulong , c_ulong ] |
## Process32First |
Process32FirstA = windll . kernel32 . Process32First |
Process32FirstA . argtypes = [ c_void_p , POINTER ( PROCESSENTRY32A ) ] |
Process32FirstA . rettype = c_int |
## Process32FirstW |
Process32FirstW = windll . kernel32 . Process32FirstW |
Process32FirstW . argtypes = [ c_void_p , POINTER ( PROCESSENTRY32W ) ] |
Process32FirstW . rettype = c_int |
## Process32Next |
Process32NextA = windll . kernel32 . Process32Next |
Process32NextA . argtypes = [ c_void_p , POINTER ( PROCESSENTRY32A ) ] |
Process32NextA . rettype = c_int |
## Process32NextW |
Process32NextW = windll . kernel32 . Process32NextW |
Process32NextW . argtypes = [ c_void_p , POINTER ( PROCESSENTRY32W ) ] |
Process32NextW . rettype = c_int |
## OpenProcess |
OpenProcess = windll . kernel32 . OpenProcess |
OpenProcess . argtypes = [ c_ulong , c_int , c_ulong ] |
OpenProcess . rettype = c_void_p |
## GetPriorityClass |
GetPriorityClass = windll . kernel32 . GetPriorityClass |
GetPriorityClass . argtypes = [ c_void_p ] |
GetPriorityClass . rettype = c_long |
## CloseHandle |
CloseHandle = windll . kernel32 . CloseHandle |
CloseHandle . argtypes = [ c_void_p ] |
CloseHandle . rettype = c_int |
## Module32First |
Module32FirstA = windll . kernel32 . Module32First |
Module32FirstA . argtypes = [ c_void_p , POINTER ( MODULEENTRY32A ) ] |
Module32FirstA . rettype = c_int |
## Module32FirstW |
Module32FirstW = windll . kernel32 . Module32FirstW |
Module32FirstW . argtypes = [ c_void_p , POINTER ( MODULEENTRY32W ) ] |
Module32FirstW . rettype = c_int |
## Module32Next |
Module32NextA = windll . kernel32 . Module32Next |
Module32NextA . argtypes = [ c_void_p , POINTER ( MODULEENTRY32A ) ] |
Module32NextA . rettype = c_int |
## Module32NextW |
Module32NextW = windll . kernel32 . Module32NextW |
Module32NextW . argtypes = [ c_void_p , POINTER ( MODULEENTRY32W ) ] |
Module32NextW . rettype = c_int |
## Thread32First |
Thread32First = windll . kernel32 . Thread32First |
Thread32First . argtypes = [ c_void_p , POINTER ( THREADENTRY32 ) ] |
Thread32First . rettype = c_int |
## Thread32Next |
Thread32Next = windll . kernel32 . Thread32Next |
Thread32Next . argtypes = [ c_void_p , POINTER ( THREADENTRY32 ) ] |
Thread32Next . rettype = c_int |
## GetLastError |
GetLastError = windll . kernel32 . GetLastError |
GetLastError . rettype = c_ulong |
use_unicode = True |
if use_unicode : |
Process32First = Process32FirstW |
Process32Next = Process32NextW |
Module32First = Module32FirstW |
Module32Next = Module32NextW |
PROCESSENTRY32 = PROCESSENTRY32W |
MODULEENTRY32 = MODULEENTRY32W |
else : #ANSI version |
Process32First = Process32FirstA |
Process32Next = Process32NextA |
Module32First = Module32FirstA |
Module32Next = Module32NextA |
PROCESSENTRY32 = PROCESSENTRY32A |
MODULEENTRY32 = MODULEENTRY32A |
def ListProcessModules ( ProcessID ): |
hModuleSnap = c_void_p ( 0 ) |
me32 = MODULEENTRY32 () |
me32 . dwSize = sizeof ( MODULEENTRY32 ) |
hModuleSnap = CreateToolhelp32Snapshot ( TH32CS_SNAPMODULE , ProcessID ) |
ret = Module32First ( hModuleSnap , pointer ( me32 ) ) |
if ret == 0 : |
print ( ‘ListProcessModules() Error on Module32First[%d]’ % GetLastError ()) |
CloseHandle ( hModuleSnap ) |
return False |
while ret : |
print ( » MODULE NAME: %s» % me32 . szModule ) |
print ( » executable = %s» % me32 . szExePath ) |
print ( » process > % me32 . th32ProcessID ) |
print ( » ref count (g) = 0x%04X» % me32 . GlblcntUsage ) |
print ( » ref count (p) = 0x%04X» % me32 . ProccntUsage ) |
print ( » base address = 0x%08X» % me32 . modBaseAddr ) |
print ( » base size = %d» % me32 . modBaseSize ) |
ret = Module32Next ( hModuleSnap , pointer ( me32 ) ) |
CloseHandle ( hModuleSnap ) |
return True |
def ListProcessThreads ( ProcessID ): |
hThreadSnap = c_void_p ( 0 ) |
te32 = THREADENTRY32 () |
te32 . dwSize = sizeof ( THREADENTRY32 ) |
hThreadSnap = CreateToolhelp32Snapshot ( TH32CS_SNAPTHREAD , 0 ) |
ret = Thread32First ( hThreadSnap , pointer ( te32 ) ) |
if ret == 0 : |
print ( ‘ListProcessThreads() Error on Thread32First[%d]’ % GetLastError ()) |
CloseHandle ( hThreadSnap ) |
return False |
while ret : |
if te32 . th32OwnerProcessID == ProcessID : |
print ( » THREAD > % te32 . th32ThreadID ) |
print ( » base priority = %d» % te32 . tpBasePri ) |
print ( » delta priority = %d» % te32 . tpDeltaPri ) |
ret = Thread32Next ( hThreadSnap , pointer ( te32 ) ) |
CloseHandle ( hThreadSnap ) |
return True |
# main |
if __name__ == ‘__main__’ : |
hProcessSnap = c_void_p ( 0 ) |
hProcessSnap = CreateToolhelp32Snapshot ( TH32CS_SNAPPROCESS , 0 ) |
pe32 = PROCESSENTRY32 () |
pe32 . dwSize = sizeof ( PROCESSENTRY32 ) |
ret = Process32First ( hProcessSnap , pointer ( pe32 ) ) |
while ret : |
print ( «» ) |
print ( «==================================================» ) |
print ( «Process Name : %s » % pe32 . szExeFile ) |
print ( «—————————————————» ) |
hProcess = OpenProcess ( PROCESS_ALL_ACCESS , 0 , pe32 . th32ProcessID ) |
dwPriorityClass = GetPriorityClass ( hProcess ) |
if dwPriorityClass == 0 : |
CloseHandle ( hProcess ) |
print ( » process > % pe32 . th32ProcessID ) |
print ( » thread count = %d» % pe32 . cntThreads ) |
print ( » parent process > % pe32 . th32ParentProcessID ) |
print ( » Priority Base = %d» % pe32 . pcPriClassBase ) |
print ( » Priority > % dwPriorityClass ) |
ListProcessModules ( pe32 . th32ProcessID ) |
ListProcessThreads ( pe32 . th32ProcessID ) |
ret = Process32Next ( hProcessSnap , pointer ( pe32 ) ) |
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.