I want to try capturing PyCharm's stop signal (when stop is pressed) in a try block, but I cannot figure out what this signal is or how to capture it in code. JetBrains doesn't provide insight into this in their documentation.
I've tried catching it as BaseException
but it does not seem to be an exception at all.
Is this programmatically capturable at all?
I wasn't able to replicate the other answers as the stop button being sent as a keyboard interrupt. I do believe it's possible for the stop button to be implemented differently on different versions of PyCharm and OS (I'm on Linux where a different answer seems to be Windows, but I'm not positive on many aspects here)
It seems to me that a kill signal is being sent, and it doesn't seem like catching that as an exception works (for me). However, I was able to somewhat catch a kill signal by referencing this post that talks about catching kill signals in Python and killing gracefully. Below is the code I used. When I press the stop button I see Hello world
, but I do NOT see foobar
.
Also, the debugger is NOT able to be caught for me by breakpoints in handler_stop_signals
by doing this, but I do see the text. So I'm not sure if this is actually going to answer your question or not, based on your needs. Also note I would never actually write code like this (using globals), but it was the simplest answer I was able to come up with.
import signal
import time
run = True
def handler_stop_signals(signum, frame):
global run
print("Hello world")
run = False
signal.signal(signal.SIGINT, handler_stop_signals)
signal.signal(signal.SIGTERM, handler_stop_signals)
while run:
try:
time.sleep(20) # do stuff including other IO stuff
except: BaseException as e:
print('foobar')