如何在 Python 中捕获 SIGINT 信号?


在本文中,我们将学习如何在 Python 中捕获 SIGINT 信号,以及捕获后需要执行的操作。

当 signal 模块接收到信号时,它会执行特定的操作。除此之外,它还可以使用 SIGINT 捕获用户通过键盘的中断。

所需模块

Signal 模块

术语“信号”指的是程序可以从操作系统接收信息的过程。此外,当操作系统检测到特定事件时,会将信号发送到程序。通过在终端执行以下命令,可以安装 signal 模块:

pip install signal

Sys 模块

Python 中的 sys 模块提供了一些函数和变量,用于修改 Python 运行环境的不同部分。可以使用以下命令安装 sys 模块:

pip install os-sys

Time 模块

Python 的 time 模块允许用户处理时间并记录有关时间的信息。time 模块通常预装在 Python 中,因此无需安装;但是,如果它没有安装,可以使用以下命令安装它:

pip install python-time

现在我们将逐步了解如何在 Python 中捕获 SIGINT 信号的实现。

分步实现

步骤 1:导入库

首先,我们必须使用import关键字导入所有必需的库。其中包括 signal、sys 和 sleep 库。

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

步骤 2:创建函数

现在我们创建一个函数,在发生键盘中断时,它将被调用并接受任意两个参数。在本例中,参数被指定为sigframe

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

步骤 3:定义自定义处理程序

在这里,我们使用 signal.signal() 函数来定义自定义处理程序,这些处理程序必须在接收到信号时被调用。此外,我们定义 signal.SIGINT,它会导致通过键盘输入Ctrl+CCtrl+F2来中断。

signal.signal(signal.SIGINT, signalHandling)

步骤 4:打印随机消息

接下来,打印一些随机消息,并附带几行内容,让用户知道如果键盘被中断该怎么办。

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

步骤 5:设置睡眠时间

最后,将 Python 的睡眠时间设置为随机的秒数。

# sleep time 
sleep(time in sec)

注意

程序有一个需要注意的地方:如果您在 Windows 上运行它,可以通过按Ctrl 和 F2停止它并捕获 SIGINT,但如果您在 Linux 上运行它,则可以通过同时按Ctrl 和 C停止它。

在 Python 中捕获 SIGINT

算法(步骤)

以下是执行所需任务应遵循的算法/步骤:-

  • 使用 import 关键字导入signalsys模块。

  • 使用 import 关键字从 time 模块导入sleep函数。

  • 创建一个变量并将其值初始化为 1(它用于表示循环执行的次数)。

  • 使用while True,无限循环。

  • 使用 try-except 块处理错误/异常。

  • 打印循环执行次数,方法是打印上述变量。

  • 使用sleep()函数在打印每个数字之间休眠随机秒数,并将数字作为参数传递给它。

  • 将循环执行计数值加 1。

  • 使用except块处理键盘中断异常。

  • 如果发生键盘中断异常,则打印任何消息。

  • 使用 sys 模块的exit()函数关闭/退出程序。

示例

以下程序使用 try/catch 异常捕获 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()

输出

执行上述程序后,将生成以下输出:

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

在此程序中,我们使用 try-catch 语句来处理键盘异常。在 try 块中运行递增数字循环时,我们在 catch 块中捕获了键盘中断。

结论

在本文中,我们学习了如何使用 Python 捕获 SIGINT。我们学习了如何使用 try/catch 语句来实现相同的功能。try 和 catch 语句可用于处理除以零和键盘中断等异常。

更新于:2023年1月24日

1K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.