Posts: 84
Joined: Thu Oct 25, 2012 1:40 am
Location: Toronto, Ontario, Canada

How do I catch a shutdown in a Python script

Mon Jan 05, 2015 8:56 pm

I have a python script that is running continuously to poll a magnetic door switch. This script will start at system bootup.

I have implemented some python code to catch a Keyboard Interrupt (aka Ctrl-c) but what's the best way in Python of catching a system shutdown so that I can clean up open files, dbs, etc before the system shuts down?

User avatar
Posts: 1549
Joined: Tue May 28, 2013 3:24 pm
Location: North Texas

Re: How do I catch a shutdown in a Python script

Tue Jan 06, 2015 6:25 am

Write a init script that will send a signal to your process. Trap that signal and then your program can exit cleanly, flush buffers, etc. In addition your script can shut down the database, etc.
Doing Unix since 1985.
The 9-25-2013 image of Wheezy can be found at:

Posts: 7882
Joined: Mon Dec 12, 2011 8:30 pm
Location: Germany

Re: How do I catch a shutdown in a Python script

Tue Jan 06, 2015 6:42 am

As dougie said , use UNIX signals. As part of the Linux/UNIX
shutdown process all programs recieve a SIGTERM signal which
they should catch and act upon ASAP (two seconds on my
system). After that the programs get killed (you can't catch a kill
signal). You can catch UNIX signals with the Python signal

A custom init script buys you some more time.
http://stackoverflow.com/questions/8617 ... er-to-fini

• Don't like the board ? Missing features ? Change to the prosilver theme ! You can find it in your settings.
• Don't like to search the forum BEFORE posting 'cos it's useless ? Try googling : yoursearchtermshere site:raspberrypi.org

Return to “Raspberry Pi OS”