Can this be stopped from leaking memory?

John Grayson johngrayson at home.com
Fri Jun 9 07:14:49 EDT 2000


In article <393FFFE7.1887276C at ebeon.com>,
  Niall Smart <niall.smart at ebeon.com> wrote:
> Hi,
>
> I'm wondering if this can be stopped from leaking memory?
>
> import imp
> import time
>
> for i in range(0, 20000):
>         fn = "mod.pyc"
>         m = imp.load_module(str(time.time()), open(fn, "rb"), fn,
(".pyc", "rb", imp.PY_COMPILED))
>         m.main()
>
> Where mod.py is:
>
> def main():
> 	print "foo"
>
> or something else trivial.
>
>

The first argument to load_module is the module NAME,
so I don't see how 'str(time.time()) satisfies the module
name.

*This* does not leak...

import imp

fn = "mod.pyc"
for i in range(0, 20000):
    m = imp.load_module('Mod', open(fn, "rb"), fn, (".pyc", "rb", \
                                                imp.PY_COMPILED))
    m.main()

However, this leaves the file descriptor dangling (further reading of
the documentation reveals:

Important: the caller is responsible for closing the dile argument,
if it was not None, even when an exception is raised. ...

So, this is probably better:

import imp

fn = "mod.pyc"

for i in range(0, 20000):
    fd = open(fn, "rb")
    m = imp.load_module('Mod', fd, fn, (".pyc", "rb", imp.PY_COMPILED))
    fd.close()
    m.main()



Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list