0

In my case, I am handling databases throughout the entire runtime of my program, and so I need to keep my 'cursor' open for the entire program. Is there anyway I can implement a termination protocol, so that when I terminate its execution or an error arises, I am able to run this quick piece of code that simply closes the cursor (I am using python sockets btw).

I would suspect I could do something like this:

if __name__ == "__main__":
    Menu()
    cursor.close()

However, the only reason that this doesn't work in my case is that Menu is simply starting up threads, and so its execution continues on, returning me back to cursor.close() whilst my program continues to run.

I'm not sure if there is a way to get around this problem.

martineau
  • 119,623
  • 25
  • 170
  • 301
0isab
  • 67
  • 2
  • 7

2 Answers2

2

Yes, you could use the signal library in python to achieve some of this functionality, in particular, capturing program termination as well interrupts to the program like ctrl + c. Example:

# a function to register the signal handlers
# once the program terminates or is halted by an interrupt like ctrl + c it executes the quit_gracefully function
def register_signal_handler():
    signal.signal(signal.SIGINT, quit_gracefully)
    signal.signal(signal.SIGTERM, quit_gracefully)
    return

def quit_gracefully():
   # close connections etc.

in case of a different error you could use a try-except block which handles the error and runs the quit_gracefully function in the except.

try:
  # some code
except:
  quit_gracefully()

EDIT:

this is a good post on signal. How do I capture SIGINT in Python?

Souldiv
  • 145
  • 1
  • 5
1

You can also use the atexit module: https://docs.python.org/3/library/atexit.html.

Something like this:

import atexit

@atexit.register
def close_cursor():
    print("Closing cursor before exiting.")
    cursor.close()
expectedAn
  • 96
  • 9