Shutdown hook

S

Steve

Does any one know if python has the ability to run a shutdown hook.

For example you set a method to run when the python process is shutting
down, like it recieved a kill signal?

Basically looking for an effect like the following java code.
Runtime.getRuntime().addShutdownHook(new Thread(this));
 
B

Ben Finney

Steve said:
Does any one know if python has the ability to run a shutdown hook.

When the Python runtime system wants to exit, it raises a SystemExit
exception.

Catch that exception at the top level of your code, and do whatever
you like. (It might be polite to actually exit at some point, of
course. sys.exit(exitcode) will do so -- raising another SystemExit
exception.)
 
L

Lawrence Oluyede

Il 2005-11-15 said:
When the Python runtime system wants to exit, it raises a SystemExit
exception.

Catch that exception at the top level of your code, and do whatever
you like. (It might be polite to actually exit at some point, of
course. sys.exit(exitcode) will do so -- raising another SystemExit
exception.)

I think using atexit module -
http://docs.python.org/lib/module-atexit.html is cleaner
 
D

Duncan Booth

Lawrence said:
I think using atexit module -
http://docs.python.org/lib/module-atexit.html is cleaner
Correct, although this won't catch all cases where a program is exiting.
For example, on Windows, if you use Ctrl+C to terminate a program the
atexit function *is* called, but if you use Ctrl+Break the atexit function
is not called unless you install a suitable signal handler:

import signal
def sigbreak(signum, frame):
sys.exit("***break")

signal.signal(signal.SIGBREAK, sigbreak)

Even then there are still other ways to terminate a process which will not
be caught.
 
S

Steve Juranich

Does any one know if python has the ability to run a shutdown hook.

Look at the "atexit" module.

barbet (~)$ pydoc atexit.register
Help on function register in atexit:

atexit.register = register(func, *targs, **kargs)
register a function to be executed upon normal program termination

func - function to be called at exit
targs - optional arguments to pass to func
kargs - optional keyword arguments to pass to func
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top