簡體   English   中英

按下 Ctrl-C 時,Python 腳本避免退出

[英]Python script avoid quitting when Ctrl-C is pressed

我正在嘗試出於教育目的運行WifiPhisher 在一個步驟中,它說按 Ctrl-C 輸入一個數字。 現在,當我按 Ctrl-c 時,腳本會退出,正如我在 github 上的這個問題中所描述的那樣。 而理想情況下,腳本不應退出,而應在按下 Ctrl-C 后繼續執行邏輯。 我不熟悉 Python,誰能幫我解決這個問題?

您可以將signal handler設置為CTRL-C信號以關閉引發KeyboardInterrupt異常的默認signal handler

import signal, os

def handler(signum, frame):
    print 'Signal handler called with signal', signum

# Set the signal handler
signal.signal(signal.SIGINT, handler)

Ctrl-C (在較舊的 Unix 中,DEL)發送一個 INT 信號(SIGINT); 默認情況下,這會導致進程終止

SIGINT當用戶希望中斷進程時,SIGINT 信號由其控制終端發送到進程。 這通常通過按 Control-C 啟動,但在某些系統上,可以使用“刪除”字符或“中斷”鍵。 [6]

https://docs.python.org/2/library/signal.html

您需要捕獲一個 KeyboardInterrupt 並處理它。

非常基本的例子:

try:
    while True:
        print "Hello world"
except KeyboardInterrupt:
    print "Goodbye"
    exit(0)

將此用於重復性任務。 但是在 Linux 中,當按下 Ctrl-C 時它會顯示“^C”。 (在 Windows Store 應用程序 Ubuntu 上測試,應該適用於許多平台)

def repeat():
    try:
        import time
        x=0
        while x==0:
            print("This is text")
            time.sleep(0.1)
    except KeyboardInterrupt:
        repeat()
repeat()

暫無
暫無

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

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