How to kill a process using Python

Published on Aug. 22, 2023, 12:14 p.m.

To kill a process using Python, you can use the os module’s kill() function to send a SIGTERM signal to the process ID you want to terminate. Here’s an example:

import os

# get the process ID of the process you want to kill
pid = 12345

# send a SIGTERM signal to the process
os.kill(pid, signal.SIGTERM)

You can also use the subprocess module to run system commands, including commands to kill processes. Here’s an example of using subprocess to kill a process by name:

import subprocess

# kill a process by name
subprocess.call(['pkill', 'process_name'])

You can replace ‘process_name’ with the name of the process you want to kill. Keep in mind that killing processes indiscriminately can lead to unexpected behavior and data loss, so be careful when using these methods.

There are several other ways to kill a process in Python, depending on what you are looking for.

If you want a more specific way of killing processes, you can use the psutil module to get more detailed information about running processes and terminate them. Here’s an example:

import psutil

# get all running processes
processes = psutil.process_iter()

# loop through processes and terminate the one with a specific name
for process in processes:
    if process.name() == "process_name":
        process.terminate()

Alternatively, you can use the taskkill command in Windows or the pkill command in Linux/Unix to kill a process by name. Here’s an example using subprocess:

import subprocess

# kill a process by name using the taskkill or pkill command
subprocess.run(["taskkill", "/f", "/im", "process_name.exe"]) # for Windows
subprocess.run(["pkill", "process_name"]) # for Linux/Unix

Keep in mind that killing processes indiscriminately can lead to unexpected behavior and data loss, so be careful when using these methods.

Tags:

related content