arbulgazar arbulgazar - 1 year ago 318
Python Question

Keyboard interrupt in debug mode PyCharm

Is there any way to send a keyboard interrupt event in PyCharm IDE (3.1) while in the debugging mode?

Answer Source

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:
        print "Zzzz"
    except KeyboardInterrupt as e:
        print "Closed by an Interrupt"

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download