Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Get the list of Running Processes using Python?
The operating system runs with hundreds of tasks/processes at a single time. As a Python developer, this is important because often while dealing with programs that consume huge amounts of memory, we may want to delete some unimportant tasks. This article will explore how to get the running process list using Python.
Using psutil Module
The psutil module is a powerful cross?platform library for system monitoring and process management in Python. It provides a convenient and consistent API to access system?related information, such as CPU usage, memory utilization, disk usage, network statistics, etc. Being cross?platform, the same code applies to all the operating systems.
Basic Process Listing
In the following code, we first import the psutil library. Next, we use the process_iter() method which returns all the processes running in the system ?
import psutil
processes = psutil.process_iter()
for process in processes:
print(f"Process ID: {process.pid}, Name: {process.name()}")
Process ID: 1, Name: systemd Process ID: 2, Name: kthreadd Process ID: 3, Name: rcu_gp Process ID: 4, Name: rcu_par_gp Process ID: 5, Name: slub_flushwq Process ID: 6, Name: netns Process ID: 1234, Name: python Process ID: 5678, Name: firefox
Getting Detailed Process Information
We can also retrieve additional information like CPU usage, memory usage, and process status ?
import psutil
for process in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
try:
info = process.info
print(f"PID: {info['pid']}, Name: {info['name']}, CPU: {info['cpu_percent']}%, Memory: {info['memory_percent']:.2f}%")
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
PID: 1, Name: systemd, CPU: 0.0%, Memory: 0.12% PID: 2, Name: kthreadd, CPU: 0.0%, Memory: 0.00% PID: 1234, Name: python, CPU: 2.5%, Memory: 1.45% PID: 5678, Name: firefox, CPU: 8.2%, Memory: 15.67%
Using Subprocess and Platform Module
Subprocess and platform modules are two important modules in Python that deal with the operating system. The subprocess allows the coders to interact with the operating system and execute external commands. The platform module gives us information about the current operating system.
Cross-Platform Process Listing
We can use different system commands based on the operating system to list processes ?
import subprocess
import platform
command = ""
if platform.system() == "Windows":
command = "tasklist"
elif platform.system() == "Linux":
command = "ps aux"
elif platform.system() == "Darwin": # macOS
command = "ps aux"
try:
output = subprocess.check_output(command, shell=True, text=True)
print(output)
except subprocess.CalledProcessError as e:
print(f"Error executing command: {e}")
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 168556 13420 ? Ss 09:37 0:01 /sbin/init splash root 2 0.0 0.0 0 0 ? S 09:37 0:00 [kthreadd] root 3 0.0 0.0 0 0 ? I< 09:37 0:00 [rcu_gp] user 1234 2.5 1.4 45632 23456 ? S 10:30 0:05 python script.py user 5678 8.2 15.6 567890 98765 ? S 09:45 2:34 firefox
Using wmi Module (Windows Only)
The WMI (Windows Management Instrumentation) is a Python library to interact with only Windows?based systems. It provides a Python interface to access and manipulate WMI data, allowing you to retrieve information about hardware, software, processes, and more.
Example
This code works only on Windows systems and requires the wmi module to be installed ?
import wmi
wmi_obj = wmi.WMI()
processes = wmi_obj.Win32_Process()
for process in processes:
print(f"Process ID: {process.ProcessId}, Name: {process.Name}")
Process ID: 0, Name: System Idle Process Process ID: 4, Name: System Process ID: 76, Name: Registry Process ID: 244, Name: smss.exe Process ID: 328, Name: csrss.exe Process ID: 1234, Name: python.exe Process ID: 5678, Name: firefox.exe
Comparison of Methods
| Method | Cross-Platform | Installation Required | Detail Level |
|---|---|---|---|
| psutil | Yes | pip install psutil | High |
| subprocess + platform | Yes | Built-in modules | Medium |
| wmi | Windows only | pip install wmi | High |
Conclusion
The psutil module is the recommended approach for cross-platform process monitoring due to its rich features and consistent API. Use subprocess with built-in modules when you can't install external libraries, and wmi for Windows-specific advanced features.
