In a program that connects to a DB,
If you receive SIGINT(ctrl+c)
, it doesn't turn off immediately
You have to close the program after organizing what is related to the DB.
I don't know when SIGINT
will come in, so I'm going to read the entire script
I don't think it's good to wrap it up with try-exception
.
Perl used this method, but what should I do with Python?
$SIG{'INT'} = = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
After making the DB cleanup code into a handler function,
signal.You must register this handler with signal().
In the case of windows, only SIGABRT
, SIGFPE
, SIGILL
, SIGINT
, SIGSEGV
, and SIGTERM
can be written.
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame): #SIGINTHandlerDefinition
print('You pressed Ctrl+C!')
#DB Cleanup Code
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler) #Registration
print('Press Ctrl+C')
signal.pause()
© 2024 OneMinuteCode. All rights reserved.