1:source: http://www.pytables.org/moin/UserDocuments/AtexitHooks
2:revision: 2
3:date: 2012-06-01 09:31:14
4:author: AskJakobsen
5
6========================
7Tailoring `atexit` hooks
8========================
9
10In some situations you may want to tailor the typical messages that PyTables
11outputs::
12
13    Closing remaining open files: /tmp/prova.h5... done
14
15The responsible of this behaviour is the :func:`tables.file.close_open_files`
16function that is being registered via :func:`atexit.register` Python function.
17Although you can't de-register already registered cleanup functions, you can
18register new ones to tailor the existing behaviour.
19For example, if you  register this function::
20
21    def my_close_open_files(verbose):
22        open_files = tables.file._open_files
23
24        are_open_files = len(open_files) > 0
25
26        if verbose and are_open_files:
27            sys.stderr.write("Closing remaining open files:")
28
29        if StrictVersion(tables.__version__) >= StrictVersion("3.1.0"):
30            # make a copy of the open_files.handlers container for the iteration
31            handlers = list(open_files.handlers)
32        else:
33            # for older versions of pytables, setup the handlers list from the
34            # keys
35            keys = open_files.keys()
36            handlers = []
37            for key in keys:
38                handlers.append(open_files[key])
39
40        for fileh in handlers:
41            if verbose:
42                sys.stderr.write("%s..." % fileh.filename)
43
44            fileh.close()
45
46            if verbose:
47                sys.stderr.write("done")
48
49        if verbose and are_open_files:
50            sys.stderr.write("\n")
51
52    import sys, atexit
53    from distutils.version import StrictVersion
54    atexit.register(my_close_open_files, False)
55
56then, you won't get the closing messages anymore because the new registered
57function is executed before the existing one.
58If you want the messages back again, just set the verbose parameter to true.
59
60You can also use the `atexit` hooks to perform other cleanup functions as well.
61
62