Keyboard interrupt in debug mode PyCharm

Unfortunately, there is no simple way to do this. You will need to use psutil and the signal module. For this to work you need to install psutil and the best way to do that is through pip:

pip install psutil

So, lets say we have here, exhibit A:

while True:
    try:
        time.sleep(3)
        print "Zzzz"
        time.sleep(3)
        print("gong!")
    except KeyboardInterrupt as e:
        print "Closed by an Interrupt"
        break

And you're running this in PyCharm. Make sure that the interpreter you're using has psutils installed. You can check:

enter image description here

Make sure you've set your interpreter correctly:

enter image description here

If you haven't installed psutil, you can always do so though the Install button.

Okay then, so now that we have everything set up, lets debug the program:

enter image description here

Now all we have to do is get the process ID, and we can get that at the very start of the program:

enter image description here

So, lets fire up our console, and send a signal:

enter image description here

And if that worked properly, you should see the while loop ending:

enter image description here

You can further streamline the process by adding a function to send an interrupt in the starting script for your console:

enter image description here

Once you're done with all of that, all you need to do is call interrupt(<pid here>) to call a keyboard interrupt on your process.

I hope that answers your question.


This is a bug in PyCharm. See: http://youtrack.jetbrains.com/issue/PY-4840

Keyboard interrupt is a SIGINT. On unix systems you can either go to the command line and do:

$ kill -INT <pid>

or in python:

import os, signal
os.kill(<pid>,signal.SIGINT)

PyCharm Stop button now sends SIGINT both in debug mode and run mode. If SIGINT does not terminate the program, the Stop button changes its signal to SIGKILL. It also changes its icon to a skull shape:

See how the stop button changed its icon


As mentioned in this comment - Why doesn't this python keyboard interrupt work? (in pycharm):

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.

Tested with PyCharm 2018.3 (Community Edition):

enter image description here

Also this will break tqdm library:

enter image description here