Open In App

Kill a Process by name using Python

Last Updated : 30 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Functions used: 

  • 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.  

process

Python3




import os, signal
  
def process():
     
    # Ask user for the name of process
    name = input("Enter process Name: ")
    try:
         
        # iterating through each instance of the process
        for line in os.popen("ps ax | grep " + name + " | grep -v grep"):
            fields = line.split()
             
            # extracting Process ID from the output
            pid = fields[0]
             
            # terminating process
            os.kill(int(pid), signal.SIGKILL)
        print("Process Successfully terminated")
         
    except:
        print("Error Encountered while running script")
  
process()


Output:
 

python-kill-process

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.
 


Previous Article
Next Article

Similar Reads

Python | Different ways to kill a Thread
In general, killing threads abruptly is considered a bad programming practice. Killing a thread abruptly might leave a critical resource that must be closed properly, open. But you might want to kill a thread once some specific time period has passed or some interrupt has been generated. There are the various methods by which you can kill a thread
8 min read
Python | os.kill() method
os.kill() method in Python is used to send a specified signal to the process with a specified process ID. Constants for the specific signals available on the host platform are defined in the Signal Module. os.kill() Method Syntax in PythonSyntax: os.kill(pid, sig) Parameters: pid: An integer value representing process id to which signal is to be se
2 min read
How to Kill a While Loop with a Keystroke in Python?
Loops are fundamental structures in Python programming for executing a block of code repeatedly until a certain condition is met. However, there are scenarios where you might want to terminate a while loop prematurely, especially when you want to give the user the ability to interrupt the loop with a keystroke. In this article, we'll explore some s
3 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
Python | Print the initials of a name with last name in full
Given a name, print the initials of a name(uppercase) with last name(with first alphabet in uppercase) written in full separated by dots. Examples: Input : geeks for geeks Output : G.F.Geeks Input : mohandas karamchand gandhi Output : M.K.Gandhi A naive approach of this will be to iterate for spaces and print the next letter after every space excep
3 min read
Python IMDbPY – Getting Person name from searched name
In this article we will see how we can get the person name from the searched list of name, we use search_name method to find all the related names.search_name method returns list and each element of list work as a dictionary i.e. they can be queried by giving the key of the data, here key will be name. Syntax : names[0]['name']Here names is the lis
2 min read
Python | Gender Identification by name using NLTK
Natural Language Toolkit (NLTK) is a platform used for building programs for text analysis. We can observe that male and female names have some distinctive characteristics. Names ending in a, e and i are likely to be female, while names ending in k, o, r, s and t are likely to be male. Let's build a classifier to model these differences more precis
4 min read
Name validation using IGNORECASE in Python Regex
In this article, we will learn about how to use Python Regex to validate name using IGNORECASE. re.IGNORECASE : This flag allows for case-insensitive matching of the Regular Expression with the given string i.e. expressions like [A-Z] will match lowercase letters, too. Generally, It's passed as an optional argument to re.compile(). Let's consider a
2 min read
Python | Swap Name and Date using Group Capturing in Regex
In this article, we will learn how to swap Name and Date for each item in a list using Group Capturing and Numeric Back-referencing feature in Regex . Capturing Group : Parentheses groups the regex between them and captures the text matched by the regex inside them into a numbered group i.e ([\w ]+) which can be reused with a numbered back-referenc
3 min read
Change Object Display Name using __str__ function - Django Models | Python
How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model. Object Display Name in Django Models Consider a proj
2 min read