Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute code when a Python script is closed out?

Tags:

python

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()
like image 838
Matthew Moisen Avatar asked Jul 21 '13 20:07

Matthew Moisen


People also ask

How do I run a Python process in the background?

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.

How do I keep a Python script open after command?

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.

How do you run a Python script in the background even after I log out?

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.

How does Python handle exit?

_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.


1 Answers

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.

like image 128
glglgl Avatar answered Sep 28 '22 01:09

glglgl