I have a raspberry pi that records temperature and stores them in a MySQL database on my website. I often toy with the script, so I am hitting ctrl+c
on the running script and re executing it. I would like to properly issue close()
on the database connection. How can I run a line of code when the script is exited in python?
import MySQLdb
con = MySQLdb.connect(...)
cursor = con.cursor()
# ...
#if script closes:
#con.close()
The easiest way of running a python script to run in the background is to use cronjob feature (in macOS and Linux). In windows, we can use Windows Task Scheduler. You can then give the path of your python script file to run at a specific time by giving the time particulars.
cmd /k is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k and then drag&drop the script you want to the Run dialog.
Role of nohup : nohup makes your script ignore SIGHUP , and redirects stdout/stderr to a file nohup. out, so that the command can continue running in the background after you log out. If you close the shell/terminal or log off, your command is no longer a child of that shell.
_exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc. Note: This method is normally used in the child process after os. fork() system call. The standard way to exit the process is sys.
import MySQLdb
con = MySQLdb.connect(...)
cursor = con.cursor()
try:
# do stuff with your DB
finally:
con.close()
The finally
clause is executed on success as well as on error (exception).
If you hit Ctrl-C, you get a KeyboardInterrupt
exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With