Process Management in Python: Terminating Processes by PID

Dec 04, 2025 · Programming · 9 views · 7.8

Keywords: Python | process management | PID | psutil | os module

Abstract: This article explores techniques for terminating processes by Process ID (PID) in Python. It compares two approaches: using the psutil library and the os module, providing detailed code examples and implementation steps to help developers efficiently manage processes in Linux systems. The article also discusses dynamic process management based on process state and offers improved script examples.

Introduction

In Linux systems, process management is a common task in system programming. Users may need to start or terminate other processes via Python scripts, such as based on Process ID (PID). This technical article analyzes methods for terminating processes in Python, based on Q&A data.

Using the psutil Library

psutil is a powerful third-party library offering extensive process management features. First, install psutil: pip install psutil. Then, you can create a process object using psutil.Process(pid) and call terminate() or kill() to terminate the process.

import psutil

pid = 12345  # Example PID
process = psutil.Process(pid)
process.terminate()  # or process.kill()

Additionally, psutil allows iterating through process lists and matching processes based on command-line arguments for advanced management.

Using the os Module

If avoiding external dependencies, Python's standard library modules os and signal provide basic functionality. Use os.kill(pid, signal) to send signals to a specified process, such as signal.SIGTERM (terminate) or signal.SIGKILL (force kill).

import os
import signal

pid = 12345
os.kill(pid, signal.SIGTERM)

This method is straightforward but limited in features.

Example Application: Starting or Terminating Processes

Based on the scenario from the Q&A, we can write a script that checks if a specific process is running, starts it if not, or terminates it otherwise. Use psutil to iterate processes and match command lines.

import psutil
from subprocess import Popen

# Check if the process is running
for process in psutil.process_iter():
    try:
        if process.cmdline() == ['python', 'StripCore.py']:
            print('Process found. Terminating it.')
            process.terminate()
            break
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        pass
else:
    print('Process not found: starting it.')
    Popen(['python', 'StripCore.py'])

This script enhances robustness by avoiding direct dependency on PID files.

Notes

When using psutil, note version differences; in older versions, cmdline was an attribute rather than a method. Additionally, consider permission issues when handling processes to avoid access denial errors.

Conclusion

This article covers two main methods for terminating processes by PID in Python: using the psutil library and the os module. psutil offers more robust features for complex scenarios, while the os module suits simple needs. Practical examples demonstrate how to implement dynamic process management, aiding developers in optimizing system scripts.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.