How to execute code when closing Python script?

I have a raspberry pi that records the temperature and stores them in a MySQL database on my website. I often play with a script, so I press ctrl+c on the script launch and execute it. I would like to set close() correctly to connect to the database. How to run a line of code when exiting a script in python?

 import MySQLdb con = MySQLdb.connect(...) cursor = con.cursor() # ... #if script closes: #con.close() 
+6
source share
2 answers
 import MySQLdb con = MySQLdb.connect(...) cursor = con.cursor() try: # do stuff with your DB finally: con.close() 

The finally clause is executed both on successful execution and on error (exception).

If you press Ctrl-C, you will get a KeyboardInterrupt exception.

+5
source

or

 import atexit def close_db(con): con.close() # any other stuff you need to run on exiting import MySQLdb con = MySQLdb.connect(...) # ... atexit.register(close_db, con=con) 

See here for more details.

0
source

Source: https://habr.com/ru/post/949946/


All Articles