Kill a Process by name using Python
A process is identified on the system by what is referred to as a process ID and no other process can use that number as its process ID while that first process is still running. Imagine you are a system administrator of a company and you start an application from your menu and you start using that application suddenly you notice that the application stopped working or die unexpectedly. You again try to start that application but it turns out that application never shut down completely. Since you are an administrator you type a command to Process ID and kill that process immediately. Imagine this scenario the employees of your company came to you every day complaining about the same situation since they don’t know what is PID and how to kill a process. So you came up with the idea of writing a script in Python which take input only the name of application or process and shut it down completely. You gave this script to your employees so every time this happens they don’t need to complain to you or know what is process id or how to kill the process, just enter the name, and everything will be taken care of.
- os.popen(): This method is used to opens a pip to and from command.
In the image below you can see that the process firefox is running
- os.kill(): This method in Python is used to send a specified signal to the process with specified process id.
Below is the implementation.
In the image below you can see that the process firefox is running.
"Enter process Name: "
"ps ax | grep "
" | grep -v grep"
"Process Successfully terminated"
"Error Encountered while running script"
In the image above you can see that all the instance of firefox has been terminated. The one that you seeing in the image is the instance that is being called by grep command. You can now check that your firefox browser has been shut completely.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses
are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!