[Tutor] associating two objects without ORM and processing a text file

eryksun eryksun at gmail.com
Fri Feb 15 06:38:33 CET 2013


On Thu, Feb 14, 2013 at 4:33 PM, Prasad, Ramit
<ramit.prasad at jpmorgan.com> wrote:
> My knee jerk response is a try/finally block, but I am sure there
> are better ways.

The atexit.register decorator hooks sys.exitfunc:

http://docs.python.org/2/library/atexit

Registered atexit functions are run early during interpreter
finalization. Signal handling is still enabled (e.g. SIGINT), and you
can still import. In the standard lib, logging and multiprocessing use
atexit.

In a C extension there's also Py_AtExit for registering a C function:

http://docs.python.org/2/c-api/sys.html#Py_AtExit

Calling the exitfuncs is the last task in Py_Finalize, after
everything has been torn down, so they should not use the C-API.

Example:

    import atexit
    from tempfile import NamedTemporaryFile
    from subprocess import Popen, PIPE
    from ctypes import CDLL, pythonapi

    @atexit.register
    def f():
        print "shutdown: atexit"

    # register a C function
    with NamedTemporaryFile() as so:
        p = Popen(['gcc', '-xc', '-shared', '-fPIC', '-o',
                   so.name, '-'], stdin=PIPE, stdout=so)
        p.communicate('''#include <stdio.h>
          void fc(void) {printf("shutdown: Py_AtExit\\n");}''')
        fc = CDLL(so.name).fc # keep reference
        pythonapi.Py_AtExit(fc)

    try:
        raise RuntimeError
    finally:
        print "shutdown: finally"

Output:

shutdown: finally
Traceback (most recent call last):
  File "atexit_example.py", line 20, in <module>
    raise RuntimeError
RuntimeError
shutdown: atexit
shutdown: Py_AtExit


More information about the Tutor mailing list