Skip to main content

How to Get a List of Running Processes in Python

Monitoring running processes is a common task in system administration, application monitoring, resource management, and security auditing. Whether you're building a task manager, debugging resource consumption, or automating system checks, Python provides several ways to retrieve the list of currently running processes.

In this guide, you'll learn multiple methods to get running processes in Python, ranging from cross-platform solutions to Windows-specific approaches, with practical examples and best practices.

Using psutil (Cross-Platform)

The psutil (Python System and Process Utilities) library is the most robust and cross-platform solution for process management. It works on Windows, macOS, Linux, and other Unix systems.

Installation:

pip install psutil

Example: List all running processes

import psutil

print(f"{'PID':<10} {'Name':<30} {'Status':<15}")
print("=" * 55)

for process in psutil.process_iter(['pid', 'name', 'status']):
info = process.info
print(f"{info['pid']:<10} {info['name']:<30} {info['status']:<15}")

Example output:

PID        Name                           Status
=======================================================
0 System Idle Process running
4 System running
736 services.exe running
1012 dwm.exe running
2892 explorer.exe running
5412 chrome.exe running
4488 notepad.exe running

Getting Detailed Process Information

psutil provides rich details about each process, including CPU usage, memory consumption, and more:

import psutil

print(f"{'PID':<8} {'Name':<25} {'CPU%':<8} {'Memory (MB)':<12} {'Status'}")
print("=" * 65)

for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_info', 'status']):
try:
info = proc.info
mem_mb = info['memory_info'].rss / (1024 * 1024) if info['memory_info'] else 0
print(
f"{info['pid']:<8} "
f"{info['name']:<25} "
f"{info['cpu_percent']:<8} "
f"{mem_mb:<12.1f} "
f"{info['status']}"
)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass # Process may have ended or requires elevated permissions

Example output:

PID      Name                      CPU%     Memory (MB)  Status
=================================================================
4 System 0.0 0.1 running
1012 dwm.exe 2.3 45.2 running
2892 explorer.exe 0.5 78.4 running
5412 chrome.exe 8.1 312.6 running
Why psutil is the best choice
  • Cross-platform: Works identically on Windows, macOS, and Linux.
  • Rich data: Provides CPU, memory, disk, network, and sensor information.
  • Safe iteration: process_iter() handles processes that terminate during iteration.
  • Well-maintained: Actively developed with excellent documentation.

Filtering Processes by Name

You can easily search for specific processes:

import psutil

def find_processes_by_name(name):
"""Find all running processes matching the given name."""
matching = []
for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
try:
if name.lower() in proc.info['name'].lower():
matching.append(proc.info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
return matching


# Find all Chrome processes
chrome_procs = find_processes_by_name("chrome")

print(f"Found {len(chrome_procs)} Chrome process(es):")
for p in chrome_procs:
mem_mb = p['memory_info'].rss / (1024 * 1024)
print(f" PID {p['pid']}: {p['name']} ({mem_mb:.1f} MB)")

Example output:

Found 5 Chrome process(es):
PID 5412: chrome.exe (312.6 MB)
PID 1376: chrome.exe (89.4 MB)
PID 1340: chrome.exe (156.2 MB)
PID 2216: chrome.exe (45.8 MB)
PID 3080: chrome.exe (72.1 MB)

Using subprocess (No Third-Party Dependencies)

If you cannot install third-party packages, the subprocess module can invoke operating system commands to retrieve process information.

On Windows

import subprocess

def get_running_processes_windows():
"""Get running processes using the Windows 'tasklist' command."""
result = subprocess.run(
["tasklist"],
capture_output=True,
text=True
)

if result.returncode != 0:
print(f"Error: {result.stderr}")
return

print(result.stdout)


get_running_processes_windows()

Example output:

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 8 K
System 4 Services 0 1,832 K
explorer.exe 2892 Console 1 78,456 K
chrome.exe 5412 Console 1 312,648 K

On Linux/macOS

import subprocess

def get_running_processes_unix():
"""Get running processes using the 'ps' command."""
result = subprocess.run(
["ps", "aux"],
capture_output=True,
text=True
)

if result.returncode != 0:
print(f"Error: {result.stderr}")
return

# Print the first 10 lines as a preview
lines = result.stdout.strip().split("\n")
for line in lines[:10]:
print(line)

print(f"\n... ({len(lines) - 1} total processes)")


get_running_processes_unix()

Cross-Platform with subprocess

import subprocess
import platform

def get_processes():
"""Get running processes on any platform."""
system = platform.system()

if system == "Windows":
cmd = ["tasklist"]
elif system in ("Linux", "Darwin"):
cmd = ["ps", "aux"]
else:
raise OSError(f"Unsupported OS: {system}")

result = subprocess.run(cmd, capture_output=True, text=True)
return result.stdout


print(get_processes())
Limitations of the subprocess approach
  • Output is raw text that requires manual parsing to extract structured data.
  • Command availability and output format vary across OS versions.
  • Parsing is fragile as output formatting may change between system configurations.

For structured process data, psutil is strongly preferred.

Using wmi (Windows Only)

The wmi library provides a Pythonic interface to Windows Management Instrumentation, giving access to detailed system and process information.

Installation:

pip install wmi
import wmi

def get_processes_wmi():
"""Get running processes using WMI (Windows only)."""
w = wmi.WMI()

print(f"{'PID':<10} {'Name':<35} {'Thread Count'}")
print("=" * 60)

for process in w.Win32_Process():
print(f"{process.ProcessId:<10} {process.Name:<35} {process.ThreadCount}")


get_processes_wmi()

Example output:

PID        Name                                Thread Count
============================================================
0 System Idle Process 8
4 System 222
736 services.exe 8
2892 explorer.exe 35
5412 chrome.exe 25
note

Win32_Process provides many attributes including ExecutablePath, CommandLine, CreationDate, WorkingSetSize, and more.

Common Mistake: Not Handling Process Termination During Iteration

Processes can terminate while you're iterating over them, causing errors if you access their properties directly.

Wrong approach: unhandled exceptions.

import psutil

for proc in psutil.process_iter():
# This can raise NoSuchProcess if the process terminates mid-iteration
print(proc.name(), proc.pid)

If a process exits between the iterator yielding it and your proc.name() call, you'll get a psutil.NoSuchProcess exception.

Correct approach: use info dict or handle exceptions.

import psutil

# Option 1: Use the attrs parameter (recommended)
for proc in psutil.process_iter(['pid', 'name']):
print(proc.info['pid'], proc.info['name'])

# Option 2: Handle exceptions explicitly
for proc in psutil.process_iter():
try:
print(proc.pid, proc.name())
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
note

Passing attrs to process_iter() caches the requested attributes in proc.info, which is both safer and faster than calling individual methods.

Quick Comparison of Methods

MethodCross-PlatformStructured DataInstallationBest For
psutil✅ All OS✅ Rich objectspip install psutilProduction use (recommended)
subprocess✅ All OS❌ Raw textNone (built-in)Quick scripts, no dependencies
wmi❌ Windows only✅ WMI objectspip install wmiWindows-specific administration

Conclusion

Python provides several ways to retrieve the list of running processes, each suited to different scenarios:

  • psutil is the recommended approach for most use cases: it is cross-platform, provides structured data with rich process details, and handles edge cases like process termination gracefully.
  • subprocess with system commands (tasklist, ps) works without third-party dependencies but requires manual output parsing.
  • wmi offers deep Windows-specific integration through Windows Management Instrumentation.

For production applications, always handle NoSuchProcess and AccessDenied exceptions, and prefer process_iter() with explicit attrs for both safety and performance.