[Python-Dev] Proposal: standard way of defining and executing
"atexit" functions...
M.-A. Lemburg
mal@lemburg.com
Tue, 20 Jun 2000 11:01:50 +0200
This is a multi-part message in MIME format.
--------------23EABAE62CA66BEF28D4AF1B
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Attached you find a similar module which I have used for years.
It has all the requested features, plus allows deregistration
and supports a more OO-like interface.
--
Marc-Andre Lemburg
______________________________________________________________________
Business: http://www.lemburg.com/
Python Pages: http://www.lemburg.com/python/
--------------23EABAE62CA66BEF28D4AF1B
Content-Type: text/python; charset=us-ascii;
name="ExitFunctions.py"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="ExitFunctions.py"
""" Central Registry for sys.exitfunc()-type functions
"""
__version__ = "0.1"
__package_info__ = """
BEGIN PYTHON-PACKAGE-INFO 1.0
Title: Central Registry for sys.exitfunc()-type functions
Current-Version: 0.1
Home-Page: http://starship.skyport.net/~lemburg
Primary-Site: http://starship.skyport.net/~lemburg/ExitFunctions.py
END PYTHON-PACKAGE-INFO
"""
import sys,traceback
class ExitFunctionDispatcher:
""" Singleton that manages exit functions. These function will be
called upon system exit in reverse order of their registering.
"""
def __init__(self):
""" Install the dispatcher as sys.exitfunc()
"""
self.exitfunc_list = []
if hasattr(sys,'exitfunc'):
self.old_exitfunc = sys.exitfunc
else:
self.old_exitfunc = None
sys.exitfunc = self.exitfunc
def exitfunc(self,
write=sys.stderr.write,print_exc=traceback.print_exc,
stderr=sys.stderr):
""" This is the exitfunc that we install to dispatch the
processing to the registered other functions
"""
for f in self.exitfunc_list:
try:
f()
except:
write('Error while executing Exitfunction %s:\n' % f.__name__)
print_exc(10,stderr)
# Now that we're finished, call the previously installed exitfunc()
if self.old_exitfunc:
self.old_exitfunc()
def register(self,f,position=0):
""" Register f as exit function. These functions must not take
parameters.
- position = 0: register the function at the beginning of the
list; these functions get called before the functions already
in the list (default)
- position = -1: register the function at the end of the list;
the function will get called after all other functions
"""
if position < 0:
position = position + len(self.exitfunc_list) + 1
self.exitfunc_list.insert(position,f)
def deregister(self,f):
""" Remove the function f from the exitfunc list; if it is not
found, the error is silently ignored.
"""
try:
self.exitfunc_list.remove(f)
except:
pass
# Create the singleton
ExitFunctions = ExitFunctionDispatcher()
--------------23EABAE62CA66BEF28D4AF1B--