Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...