Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My Python try/except loop does not seem to trigger a keyboard interrupt when Ctrl + C is pressed while debugging my code in PyCharm. (The same issue occurs when using Ctrl + C while running the program, but not in the PyCharm Python console.)

My code look like this:

try:
    while loop:
        print("busy")

except KeyboardInterrupt:
    exit()

The full code can be viewed here. The code above produces the same error.

like image 466
Edwin Shepherd Avatar asked Sep 30 '16 17:09

Edwin Shepherd


3 Answers

PyCharm's Python Console raises the exception console_thrift.KeyboardInterruptException on Ctrl-C instead of KeyboardInterrupt. The exception console_thrift.KeyboardInterruptException is not a subclass of KeyboardInterrupt, therefore not caught by the line except KeyboardInterrupt.

Adding the following lines would make your script compatible with PyCharm.

try:
    from console_thrift import KeyboardInterruptException as KeyboardInterrupt
except ImportError:
    pass

This would not break compatibility with running the script in a terminal, or other IDE, like IDLE or Spyder, since the module console_thrift is found only within PyCharm.

like image 154
Friedrich S Avatar answered Oct 21 '22 10:10

Friedrich S


I know this is an old question, but I ran into the same problem and think there's an easier solution:

In PyCharm go to "Run"/"Edit Configurations" and check "Emulate terminal in output console". PyCharm now accepts keyboard interrupts (make sure the console is focused).

Tested on: PyCharm 2019.1 (Community Edition)

like image 22
RawkFist Avatar answered Oct 21 '22 09:10

RawkFist


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.

like image 13
tdelaney Avatar answered Oct 21 '22 09:10

tdelaney