当按下ctrl+C时,我怎么能不停止程序?

2024-04-26 14:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

当用户按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,但没有给出预期的输出


Tags: 代码用户程序younotrunningpressctrl
2条回答

您可以在try&;中轻松实施下一步;除了或在后面设置一个pass

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

将其移动到循环中,因为我猜您希望继续循环而不是退出:

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

相关问题 更多 >