Home >Backend Development >Python Tutorial >How to catch SIGINT signal in Python?

How to catch SIGINT signal in Python?

PHPz
PHPzforward
2023-09-17 10:29:021010browse

How to catch SIGINT signal in Python?

In this article, we will learn how to catch SIGINT in Python and what you need to do after catching it.

After receiving the signal, the signal module will perform certain actions. In addition to this, it can also capture user interrupts via keyboard using SIGINT.

Required modules

Signal module

Terminology "Signal" refers to the process by which a program can receive information from the operating system. Additionally, signals are sent to programs when the operating system detects specific events. The signal module can be installed by executing the following command in the terminal -

pip install signal

System module

The sys module in Python provides multiple functions and variables to change different parts of the Python running environment. The sys module can be installed using the following command -

pip install os-sys

Time module

Python's time module enables users to manipulate time and record information about time. The time module usually comes pre-installed with Python, so it does not need to be installed; however, if not, you can install it using the following command -

pip install python-time

Let’s introduce step by step the implementation of capturing SIGINT in Python.

Step by step implementation

Step 1: Import the library

First, we must import all required libraries using the import keyword. The signal, sys and sleep libraries are among them.

# importing signal and sys modules 
import signal
import sys
# importing sleep function from the time module
from time import sleep

Step 2: Create the function

We now create a function that will be called in case of keyboard interruption by accepting any two parameters. In this example, the parameters are considered sig and frame.

# creating a function that accepts the two arguments 
# it is called when the user makes a keyboard interruption
def signalHandling(signal, frame):

Step 3: Define Custom Handler

Here we use the signal.signal() function to define a custom handler that must be called when the signal is received. Additionally, we define signal.SIGINT, which causes an interrupt by typing Ctrl C or Ctrl F2 on the keyboard.

signal.signal(signal.SIGINT, signalHandling)

Step 4: Print Random Message

Next, print any few lines of random messages to let the user know what to do if the keyboard is interrupted.

# printing random message
print(' printing random messages')

Step 5: Set sleep time

Finally, set the Python sleep time to a random number of seconds.

# sleep time 
sleep(time in sec)

Notice

There is a problem with this program: if you run it on Windows you can stop it and catch SIGINT by pressing Ctrl and F2, but if you run it on Linux you can stop it Press Ctrl and C simultaneously.

Capturing SIGINT in Python

Algorithm (steps)

Below are the algorithms/steps that need to be followed to perform the required task. -

  • Use the import keyword to import the signal and sys modules.

  • Use the import keyword to import the sleep function from the time module.

  • Create a variable and initialize its value to 1 (used to represent the number of loop executions).

  • Use while True to loop infinitely.

  • Use try-except block to handle errors/exceptions.

  • Print the number of loop executions by printing the above variables.

  • Use the sleep() function to sleep for a random number of seconds between printing each number by passing a number to it as an argument.

  • Add 1 to the loop execution count value.

  • Use except block to handle keyboard interrupt exceptions.

  • If a keyboard interrupt exception occurs, print any message.

  • Use the exit() function of the sys module to close/exit the program.

Example

The following program uses try/catch exception capture SIGINT -

# importing signal and sys modules
import signal
import sys
# importing sleep function from the time module
from time import sleep
# initializing variable with value 1 to count the number of times the loop is executed
k = 1
# looping infinite times using a while loop
while True:
   # using try-except blocks for handling errors/exceptions
   try:
      # Printing the count of the number of times the loop is executed
      print(k)
      #sleeping for a random number of seconds time between printing of a number
      sleep(0.5)
      # Incrementing the loop execution count by 1
      k += 1
   # Handling the keyboard interruption exception using except block
   except KeyboardInterrupt:
      # printing any message if keyboard interruption exception occurs
      print("The loop has stopped!!")
      # closing/exiting the program
      sys.exit()

Output

When executed, the above program will generate the following output -

1
2
3
4
5
6
7
8
9
10
11
12
13
The loop has stopped!!

In this program, we use the try-catch statement to handle keyboard exceptions. While running the number incrementing loop in the try block, we caught the keyboard interrupt in the catch block.

in conclusion

In this article, we learned how to capture SIGINT using Python. We learned how to use try/catch statements to achieve the same purpose. Try and catch statements can be used to handle exceptions such as division by 0 and keyboard interrupts.

The above is the detailed content of How to catch SIGINT signal in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete