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:
Make sure you've set your interpreter correctly:
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:
Now all we have to do is get the process ID, and we can get that at the very start of the program:
So, lets fire up our console, and send a signal:
And if that worked properly, you should see the while loop ending:
You can further streamline the process by adding a function to send an interrupt in the starting script for your console:
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…