Why doesn't this python keyboard interrupt work? (in pycharm)

本秂侑毒 提交于 2019-12-17 16:37:09

问题


My python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in pycharm. My code look like this:

numbers = []
loop = True

try: 
    # ===========SUBROUTINES==================

    def help():
        print("To view the list type 'view'"
              "\n To add an item type 'add'"
              "\n To remove an item type 'remove'"
              "\n To exit type exit or Ctrl + c can be used at any time")

    # =========SUBROUTENES END===============


    while loop:
        task = input("What do you want to do? Type \"help\" for help:- ")
        if task == 'help':
            help()
        else:
            print("Invalid return please try again.")

    except KeyboardInterrupt:
        exit()

EDIT: There seems to be some problems with my slimmed down code working and not producing the same error. The full code can be viewed here. I have also re-slimed down the code (The code above) and it has produced the same error.


回答1:


From your screen shot it appears that you are running this code in an IDE. The thing about IDEs is that they are not quite the same as running normally, especially when it comes to handling of keyboard characters. The way you press ctrl-c, your IDE thinks you want to copy text. The python program never sees the character. Pehaps it brings up a separate window when running? Then you would select that window before ctrl-c.




回答2:


Here is working normally, since i put a variable "x" in your code and i use tabs instead spaces.

try:

    def help():
        print("Help.")

    def doStuff():
        print("Doing Stuff")

    while True:
        x = int(input())
        if x == 1:
            help()
        elif x == 2:
            doStuff()
        else:
            exit()

except KeyboardInterrupt:
    exit()



回答3:


If that comment doesn't solve your problem, (from @tdelaney) you need to have your shell window focused (meaning you've clicked on it when the program is running.) and then you can use Control+C




回答4:


Make sure the window is selected when you press ctrl+c. I just ran your program in IDLE and it worked perfectly for me.



来源:https://stackoverflow.com/questions/39796689/why-doesnt-this-python-keyboard-interrupt-work-in-pycharm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!