20

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.

3
  • 3
    Your posted code has a bug (x is not defined) and when I add x = 2 it prints "Doing Stuff" until I press ctrl-c, then it exits. I can't reproduce your problem on linux.
    – tdelaney
    Commented Sep 30, 2016 at 17:16
  • The new code still works when run from the shell.
    – tdelaney
    Commented Sep 30, 2016 at 17:32
  • When running from shell I get SyntaxError: multiple statements found while compiling a single statement Commented Sep 30, 2016 at 17:39

9 Answers 9

26

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)

13

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.

5
  • 10
    Just for anyone who wants to use this question: the keyboard interrupt shortcut in pycharm is Ctrl + F2 Commented Sep 30, 2016 at 17:52
  • 15
    No, Ctrl-F2 is equivalent to pressing the PyCharm 'stop' button. This doesn't send a keyboard interrupt - so your process will simply stop, rather than exiting via any necessary cleanup. Commented Dec 22, 2016 at 16:11
  • 12
    In recent versions of PyCharm, you can enable Emulate terminal in output console in your Run Configuration - this allows Ctrl + C in the Run console to send a keyboard interrupt. Commented Jun 8, 2017 at 14:59
  • Emulate terminal in output console does seem to work in this case, but I have to hit 'enter' after ctrl^c, so it's not quite the same as on the command line. Unfortunately it does not seem to work reliably in other cases. I don't have a simple one to share, but it seems that ctrl c has no effect on my script. Not sure why.
    – poleguy
    Commented Aug 31, 2017 at 18:22
  • 1
    @ChristopherGurnee Thank you for that. I've been dealing with improperly terminating threads as a result of Pycharm's "stop" button since I couldn't figure out how to get SIGINT in there.
    – Derek
    Commented Feb 9, 2018 at 12:56
5

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.

2

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

5
  • I have however all that does is highlight the printed statement. See this: imgur.com/M43LPuu Commented Sep 30, 2016 at 17:29
  • @Edwinthebreadwin - let us know what IDE you are using. Its likely intercepting ctrl-c and doing something else.... like copying!
    – tdelaney
    Commented Sep 30, 2016 at 17:35
  • I'm using pycharm community edition but I have just run it in IDLE and that doesn't work either imgur.com/a/ZKAus Commented Sep 30, 2016 at 17:37
  • Yes it is copying, any idea how to stop this? Commented Sep 30, 2016 at 17:40
  • Ignoring the accepted answer in this post stackoverflow.com/questions/22913490/…, the other answer says that you just press the STOP button. I don't have pycharm and can't test.
    – tdelaney
    Commented Sep 30, 2016 at 17:45
2

You can also use PyCharm's Python console and use Ctrl + C, if you catch the exception that PyCharm raises when Ctrl + C is pressed. I wrote a short function below called is_keyboard_interrupt that tells you whether the exception is KeyboardInterrupt, including PyCharm's. If it is not, simply re-raise it. I paste a simplified version of the code below.

When it is run:

  • type 'help' and press Enter to repeat the loop.
  • type anything else and press Enter to check that ValueError is handled properly.
  • Press Ctrl + C to check that KeyboardInterrupt is caught, including in PyCharm's python console.

Note: This doesn't work with PyCharm's debugger console (the one invoked by "Debug" rather than "Run"), but there the need for Ctrl + C is less because you can simply press the pause button.

I also put this on my Gist where I may make updates: https://gist.github.com/yulkang/14da861b271576a9eb1fa0f905351b97

def is_keyboard_interrupt(exception):
    # The second condition is necessary for it to work with the stop button
    # in PyCharm Python console.
    return (type(exception) is KeyboardInterrupt
            or type(exception).__name__ == 'KeyboardInterruptException')

try:
    def print_help():
        print("To exit type exit or Ctrl + c can be used at any time")
    print_help()

    while True:
        task = input("What do you want to do? Type \"help\" for help:- ")
        if task == 'help':
            print_help()
        else:
            print("Invalid input.")

            # to check that ValueError is handled separately
            raise ValueError()

except Exception as ex:
    try:
        # Catch all exceptions and test if it is KeyboardInterrupt, native or
        # PyCharm's.
        if not is_keyboard_interrupt(ex):
            raise ex

        print('KeyboardInterrupt caught as expected.')
        print('Exception type: %s' % type(ex).__name__)
        exit()

    except ValueError:
        print('ValueError!')
1

Try shift + control + C. It worked for me.

0

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

1
  • 1
    @Edwinthebreadwin your except statement is indented too far over. The try: and except: statements need to be indented equally in order for them to work properly. I hope this helps
    – cnmcferren
    Commented Sep 30, 2016 at 17:41
0

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()
0

One possible reason if <Strg+C> does not stop the program:

When a text is marked in the shell, <Strg+C> is interpreted as "copy the marked text to clipboard".

Just unmark the text and press <Strg+C> again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.