如何在 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+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告