To make an exception to SIGINT?

Asked 2 years ago, Updated 2 years ago, 105 views

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);
}

python control signal

2022-09-21 15:22

1 Answers

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()


2022-09-21 15:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.