簡體   English   中英

按下 ctrl+C 時如何不停止程序?

[英]How can I not stop the program when ctrl+C is pressed?

當用戶按下Ctrl + C時,我試圖不停止程序。

現在是這樣的:

(programm running)
...
(user press ctrl+c)
You pressed ctrl+c
breaks

我想要的是:

(programm running)
...
(user press ctrl+c)
You pressed ctrl+c
not breaks

我怎樣才能做到這一點? 這是不可能的嗎?

我試過這段代碼:

try:
    while True: 
        userinput = input()
        if userinput == "stop":
            break
except (KeyboardInterrupt, SystemExit):
    print('You pressed ctrl+c')

我嘗試將pass添加到except ,但它沒有給出預期的 output。

將它移動到循環內,因為我猜你想繼續循環而不是退出:

while True:
    try:
        userinput = input()
        if userinput == "stop":
            break
    except (KeyboardInterrupt, SystemExit):
        print('You pressed ctrl+c')
        # or just pass to print nothing

您可以輕松地在 try & except 中實現下一步,或者在它之后設置一個pass

while True:
    try:
        userinput = input()
        if userinput == "stop":
            break
    except (KeyboardInterrupt, SystemExit):
        # or edit it to the next state in the program.
        pass

暫無
暫無

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

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