- How to Terminate a running process on Windows in Python?
- Precautions
- Method 1:
- Python3
- Method 2:
- How to terminate process from python using pid?
- Method 1: Using the os module
- Method 2: Using the subprocess module
- Method 3: Using the taskkill command
- Conclusion
- Kill Process By PID in Python
- Need To Kill a Process by PID
- How To Kill a Process via its PID
- Kill Current Process via PID
How to Terminate a running process on Windows in Python?
Process is a program that is being executed (processed). A process may not have to be one ran explicitly by the user, it could be a system process spawned by the operating system. Any applications that execute on an operating system firstly creates a process of its own to execute. In a typical os installation, most processes are os services and background applications, that are ran to maintain the operating system, software, and hardware. In this article, we will take a look at different ways of terminating running processes on a Windows OS, through python. Firstly we would describe a python method to achieve the result and then would look at a command found in Windows Command Processor for the equivalent effect.
NOTE: This method is exclusive to Windows Operating systems. To achieve a similar effect on Linux, macOS refer to Kill command in Linux
Precautions
Terminating a concurrently running process should be done appropriately and with a conscience. As terminating a necessary process (ex. svhost, System, Windows Explorer, Antimalware Service Executable) could lead to inconsistency in operating system functionality, which could consequently lead to system crashes, blue screen of death, software malfunctioning, etc. Therefore it is generally advised to double-check the name of the applications/PID that is to be terminated beforehand.
Method 1:
Firstly, we would be using the wmi library for getting the list of the running process, and later would use this list to search for our desired process, and if found would terminate it. In order to install the module, execute the following command in the command interpreter of your operating system:
Python3
Explanation:
Firstly, we define a variable storing an integer value, which would serve to tell whether the process got terminated or not. This variable could also be used to determine how many processes under the same name have been terminated. Then, we specify the name of the process which we are willing to terminate. After which we initialize the WMI() class of wmi library. This allows us to use the methods found inside it such as WMI.Win32_Service, WMI.Win32_Process etc which are designed to perform different tasks. We would be using the WMI.Win32_Process function to get the list of running processes as wmi objects. Then we use the name attribute of the wmi object to the get name of the running process. After which we would be using primitive string matching to determine whether the name of the application matches the one specified before. If it does then we call the Terminate() method, to kill/terminate the process. After which we increment the value of ti, where the incremented value (or any non 0 value) would signify that at least one process has been terminated. After the end of the loop (when all the running processes names have been checked), we would check whether the value of variable ti is still 0 or not. If it is then no process got terminated, and we inform the user about the same using an Error message.
Method 2:
Now we would be using an inbuilt utility found inside the windows command processor named WMIC (Windows Management Instrumentation Command-Line) to terminate the running process. The command we would be using :
wmic process where name="Process_Name" delete
Where Process_Name is the name of the process that we are terminating. To implement this utility in python we would be creating an instance of Windows Command line using os.system() and would be executing the command (bypassing it as argument) over there.
Code:
How to terminate process from python using pid?
Python: how to terminate a process from Python using pid?
There are several ways to terminate a process in Python using the pid (Process ID). In this tutorial, we will cover two methods of terminating a process:
Method 1: Using the os module
You can use the psutil library to get the pid of a process.
import psutil # get the pid of a process by name pid = psutil.pid_by_name("process_name")
This sends the SIGKILL signal to the process with the given pid, which terminates the process.
Method 2: Using the subprocess module
p = subprocess.Popen(["command", "arg1", "arg2"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Note: In both the methods above, make sure the process is not already terminated before trying to terminate it again, or it will raise an error.
In addition, you can also use other library like psutil , shutil , signal for process management.
psutil.Process().kill() method is similar to os.kill() method, it also sends the SIGKILL signal to the process with the given pid, which terminates the process.
import psutil p = psutil.Process(pid) p.kill()
shutil.kill() can also use to kill a process using the pid.
from shutil import kill kill(pid)
signal.CTRL_C_EVENT and signal.CTRL_BREAK_EVENT can also use to send the signal to the process
import signal os.kill(pid, signal.CTRL_C_EVENT) os.kill(pid, signal.CTRL_BREAK_EVENT)
In addition to the methods mentioned above, there is another way to terminate a process in Python using the pid:
Method 3: Using the taskkill command
- Step 2 — Use the subprocess.run() function to execute the taskkill command and pass the pid of the process you want to terminate.
subprocess.run(["taskkill", "/F", "/PID", str(pid)])
The «/F» flag is used to forcefully terminate the process, and the «/PID» flag is used to specify the pid of the process.
This method is useful when you are running the script on a Windows operating system, as the taskkill command is a built-in command in Windows.
In addition, you can use psutil.process_iter() method to iterate over all running process, and then use .kill() method on the selected process.
import psutil for process in psutil.process_iter(): if process.name() == "process_name": process.kill()
Conclusion
In conclusion, terminating a process in Python using the pid is a simple task that can be achieved using various methods. The os and subprocess modules, the taskkill command on Windows, and the psutil library all provide ways to terminate a process using the pid. It’s important to note that when using the os.kill() function or the process object’s terminate() method, you need to make sure that the process is not already terminated before trying to terminate it again, or it will raise an error. Each method has its own advantages and disadvantages, and the best method to use depends on the specific use case and the operating system the script is being run on.
Kill Process By PID in Python
You can kill a process via its process identifier, pid, via the os.kill() function.
In this tutorial you will discover how to kill a process via its pid.
Need To Kill a Process by PID
A process is a running instance of a computer program.
Every Python program is executed in a Process, which is a new instance of the Python interpreter. This process has the name MainProcess and has one thread used to execute the program instructions called the MainThread. Both processes and threads are created and managed by the underlying operating system.
Sometimes we may need to create new child processes in our program in order to execute code concurrently.
Python provides the ability to create and manage new processes via the multiprocessing.Process class.
You can learn more about multiprocessing in the tutorial:
In multiprocessing, we may need to kill a process by its process identifier or PID.
This may be for many reasons, such as:
- The task executed by the process is no longer required.
- The process has had an error or is out of control.
- The main program is closing down due to a user request.
How can we kill a process via its pid in Python?
Run your loops using all CPUs, download my FREE book to learn how.
How To Kill a Process via its PID
You can kill a process via its pid with the os.kill() function.
The os.kill function takes two arguments, the process identifier (pid) to kill, and the signal to send to kill the process.
The signal is a constant from the signal module, such as signal.SIGINT or signal.SIGKILL.
We need to know the pid for the process that is to be killed.
This can be retrieved from the multiprocessing.Process instance for the process via the pid attribute.
The multiprocessing.Process instance may be managed by the parent process when the child process is created, or accessed via a module function such as multiprocessing.active_children() or multiprocessing.parent_process().
You can learn more about getting the process pid in the tutorial:
The SIGINT or signal interrupt can be used to terminate the target process, which is equivalent to the user pressing CONTROL-C on the process. Alternately, the SIGKILL or signal kill process can be used to terminate the process forcefully.
The difference between SIGINT and SIGKILL is that it is possible for a process to detect and handle a SIGINT, whereas a SIGKILL cannot be handled.
Now that we know how to kill a process via pid, let’s look at some worked examples.
Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet
Kill Current Process via PID
It is possible to kill the current process via pid.
This can be achieved by first getting the pid for the current process, then calling os.kill() with the pid and the signal to kill the process, such as SIGKILL.
First, we can get the pid for the current process using the os.getpid(), and report the result.