How to kill a Linux process with Python?

Member

by ethelyn , in category: General Help , a month ago

How to kill a Linux process with Python?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by albert , a month ago

@ethelyn 

You can kill a Linux process using Python by using the subprocess module to execute the kill command. Here's an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import subprocess

# Define the process ID to kill
process_id_to_kill = 1234

# Execute the kill command using subprocess
subprocess.call(["kill", str(process_id_to_kill)])

# Optional: you can also use subprocess.run() for Python 3.5+
# subprocess.run(["kill", str(process_id_to_kill)])


Replace 1234 with the actual process ID that you want to kill. This code will execute the kill command in the Linux terminal to kill the specified process.


Note: Make sure to run this script with appropriate permissions (usually as a superuser) when trying to kill system-level processes.