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?
ctrl+c
close()
import MySQLdb con = MySQLdb.connect(...) cursor = con.cursor() # ... #if script closes: #con.close()
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).
finally
If you press Ctrl-C, you will get a KeyboardInterrupt exception.
KeyboardInterrupt
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.
Source: https://habr.com/ru/post/949946/More articles:How to set screen size to 4'7 inches in bluestacks emulator? - androidHow to show uidatepicker from uitableviewcell - ioshttps://translate.googleusercontent.com/translate_c?depth=1&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/949943/fopen-fails-to-create-a-file-on-linux&usg=ALkJrhjzir3SUE8aSY0ag1nqdzF9WINHNAGetting started with JavaCC - jarConnect to SQL Server using Management Studio using Windows authentication - sql-serverFacebook API API and UIActivityViewController - iosPython "re" module not working? - pythonQuoting all elements in a window object - javascriptWhat is the difference between ConfigurationManager.GetSection and Configuration.GetSection? - c #Javascript unit testing for memory leak - javascriptAll Articles