代码之家  ›  专栏  ›  技术社区  ›  ppwater Azbilegt Chuluunbat

当python中的键盘中断时,我怎么能不停止程序呢?

  •  0
  • ppwater Azbilegt Chuluunbat  · 技术社区  · 4 年前

    当用户按下时,我试图不停止程序 Ctrl键 现在是这样的:

    (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 ,但不起作用。

    2 回复  |  直到 4 年前
        1
  •  3
  •   dpwrussell    4 年前

    把它移到循环内,我猜你想继续循环而不是退出:

    while True:
        try:
            userinput = input()
            if userinput == "stop":
                break
        except (KeyboardInterrupt, SystemExit):
            print('You pressed ctrl+c')
            # or just pass to print nothing
    
        2
  •  0
  •   Mohamed E. Faleh    4 年前

    您可以轻松地在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