簡體   English   中英

使用SIGINT殺死Python 3中的函數

[英]Using SIGINT to kill a function in Python 3

以以下代碼為例:

import signal
import time

def stop(signal, frame):
    print("You pressed ctrl-c")
    # stop counter()

def counter():
    for i in range(20):
        print(i+1)
        time.sleep(0.2)

signal.signal(signal.SIGINT, stop)
while True:
    if(input("Do you want to count? ")=="yes"):
        counter()

我如何獲得stop()函數來殺死或中斷counter()函數,使其返回提示?

輸出示例:

Do you want to count? no
Do you want to count? yes
1
2
3
4
5
6
7
You pressed ctrl-c
Do you want to count?

我正在使用Python 3.5.2。

您可以在stop引發異常,這將停止counter執行並搜索最近的異常處理程序(您在while True循環中設置的異常處理程序)。

也就是說,創建一個自定義異常:

class SigIntException(BaseException): pass

stop

def stop(signal, frame):
    print("You pressed ctrl-c")
    raise SigIntException

並在while循環中捕獲它:

while True:
    if(input("Do you want to count? ")=="yes"):
        try:        
            counter()
        except SigIntException:
            pass

並按照您需要的方式運行。

您可以使用KeyboardInterrupt異常,而不是定義自己的SIGINT處理程序:

while input("Do you want to count? ").strip().casefold() == "yes":
    try:
        counter()
    except KeyboardInterrupt:
        print("You pressed ctrl-c")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM