"Martin v. Löwis" <[EMAIL PROTECTED]> writes:

> Ben Finney schrieb:
> > Question: I have Python modules named without '.py' as the extension,
> > and I'd like to be able to import them. How can I do that?
> 
> I recommend to use imp.load_module.

I've tried this; as Patrick Maupin alludes to, it compiles the module
leaving a strangely-named file behind.

Program in a file named 'frob_foo'; no other file names needed nor
desired.

    import imp

    file_name = "frob_foo"
    module_name = 'frob_foo'

    module_file = open(file_name, 'r')
    module_desc = ("", 'r', imp.PY_SOURCE)
    module = imp.load_module(module_name, module_file, file_name, module_desc)

Result: two files, 'frob_foo' and 'frob_fooc'. I can see why this
happens, but it's not what's desired. Currently I'm going with:

    file_name = "frob_foo"
    module_name = 'frob_foo'

    from types import ModuleType
    module = ModuleType(module_name)

    module_file = open(file_name, 'r')
    exec module_file in module.__dict__

Still, the purpose is simply to get a module object out, with a named
file as input. If the 'imp' module can do that without leaving
unwanted turds behind, it seems more elegant. Can anyone suggest a way
to get the same result as the above 'exec' method, using the 'imp'
module?

-- 
 \      "...one of the main causes of the fall of the Roman Empire was |
  `\        that, lacking zero, they had no way to indicate successful |
_o__)               termination of their C programs."  -- Robert Firth |
Ben Finney

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to