Cleaning up after C module

Fredrik Lundh fredrik at pythonware.com
Mon Apr 11 03:18:34 EDT 2005


<j1k1cki at hotmail.com> wrote:

> I have a Python module written in C that spawns and kills processes
> using OS-specific mechanisms. I want to kill all spawned processes when
> the interpreter exits. I tried to wrap every spawned process in a
> Python object like this:
>
>    import cmodule
>    class Process:
>        __init__(self, execname): self.pid = cmodule.spawn(execname)
>        __del__(self): cmodule.kill(self.pid)
>
>    p = Process("foo")
>
> but this does not work, I am getting and exception inidicating that
> 'cmodule' is 'None' in '__del__()'.

module-level names may be cleaned away before your objects, so if you want
to make sure you can reach a module-level object, create your own binding:

    def__del__(self, cmodule=cmodule): cmodule.kill(self.pid)

> Moreover, the Language Reference states that "It is not guaranteed that
> __del__() methods are called for objects that still exist when the
> interpreter exits", so it looks like this approach is wrong anyway. How
> do I do this right?

the "atexit" module might be what you need.

</F> 






More information about the Python-list mailing list