How can I import a script with an arbitrary name ?

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Oct 31 01:00:52 CET 2006


leonel.gayard at gmail.com writes:

> So, I have a module with an arbitrary file name and I want to load it,
> and later access its function definitions.
> How can I do this ?  In my example, the last line will obviously not
> work.

If you want a solution that gives you an actual module object, here's
what I use:

    def make_module_from_file(module_name, file_name):
        """ Make a new module object from the code in specified file """

        from types import ModuleType
        module = ModuleType(module_name)

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

        return module

-- 
 \       "A celebrity is one who is known by many people he is glad he |
  `\                               doesn't know."  -- Henry L. Mencken |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list