Python is a quite simple and powerful programming language in the sense that it can be applied to so many areas like Scientific Computing, Natural Language Processing but one specific area of application of Python which I found quite fascinating is => Interacting with low-level hardware using os Module.
In this article, I’ll discuss How to find all of processes which are running on Operating System using Python Programming Language. This Python Code is platform independent meaning that you can use it to find processes running on Mac or Windows or Linux.
Let’s see steps which can be followed for Listing All Running Processes Using Python
- Install Python Package psutil using python3 -m pip install psutil statement on terminal/command line
- Import psutil package into Python Code using import psutil statement
- Call process_iter() Function on psutil using psutil.process_iter() statement
- psutil.process_iter() Function will return a Generator Object(containing information about all of running processes/ Process Objects) this object is also iterable
- Iterate over Generator Object using For Loop and for each process object contained by it, retrieve its name and process id using name() and pid.
Let’s put all of above 5 steps together as Python Code, which when ran will show all of processes running on Operating System.
import psutil # Get Generator object containing all running processes process_iterator = psutil.process_iter() # Iterate over Generator object to get # each process object contained by it for proc in process_iterator: try: # Get process name & pid from process object processName = proc.name() processID = proc.pid print(processName , ' ::: ', processID) except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass
Let’s me show you what this code print when I run this on my MAC laptop.