Linux/Unix > Python Essential Reference, Second Edition > 10. Execution Environment > Program Termination | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105082191050116112014099

### Program Termination

A program terminates when no more statements exist to execute in the input program, when an uncaught `SystemExit` exception is raised (as generated by `sys.exit()`), or when the interpreter receives a `SIGTERM` or `SIGHUP` signal (on UNIX). On exit, the interpreter decrements the reference count of all objects in all the currently known namespaces (and destroys each namespace as well). If the reference count of an object reaches zero, the object is destroyed and its `_ _ del_ _ ()` method is invoked. It’s important to note that in some cases the `_ _ del_ _ ()` method might not be invoked at program termination. This can occur if circular references exist between objects (in which case objects may be allocated, but accessible from no known namespace). Although Python’s garbage collector can reclaim unused circular references during execution, it isn’t normally invoked on program termination.

Because there’s no guarantee that `_ _ del_ _ ()` will be invoked at termination, it may be a good idea to explicitly clean up certain objects, such as open files and network connections. To accomplish this, add specialized cleanup methods (for example, `close()`) to user-defined objects. Another possibility is to write a termination function and register it with the `atexit` module, as follows:

    import atexit
    connection = open_connection("deaddot.com")

    def cleanup():
        print "Going away..."
        close_connection(connection)

    atexit.register(cleanup)

The garbage collector can also be invoked in this manner:

    import atexit, gc
    atexit.register(gc.collect)

One final peculiarity about program termination is that the `_ _ del_ _` method for some objects may try to access global data or methods defined in other modules. Since these objects may already have been destroyed, a `NameError` exception occurs in `_ _ del_ _`, and you may get an error such as the following:

    Exception exceptions.NameError: 'c' in <method Bar._ _ del_ _ of Bar instance at c0310>
    ignored

If this occurs, it means that `_ _ del_ _` has aborted prematurely. It also implies that it may have failed in an attempt to perform an important operation (such as cleanly shutting down a server connection). If this is a concern, it’s probably a good idea to perform an explicit shutdown step in your code, rather than relying on the interpreter to destroy objects cleanly at program termination. The peculiar `NameError` exception can also be eliminated by declaring default arguments in the declaration of the `_ _ del_ _ ()` method:

    import foo
    class Bar:
       def _ _ del_ _ (self, foo=foo):
          foo.bar()        # Use something in module foo

In some cases, it may be useful to terminate program execution without performing any cleanup actions. This can be accomplished by calling `os._exit(``status` `)`. This function provides an interface to the low-level `exit()` system call responsible for killing the Python interpreter process.When invoked, the program immediately terminates.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.