How can I import a script with an arbitrary name ?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Tue Oct 31 12:23:15 CET 2006


On Tue, 31 Oct 2006 11:00:52 +1100, Ben Finney wrote:

> 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

Isn't that awfully complicated? What's wrong with using __import__ to get
a module object?

>>> mod = __import__("math")
>>> mod
<module 'math' from '/usr/lib/python2.4/lib-dynload/mathmodule.so'>


The only advantage (or maybe it is a disadvantage?) I can see to your
function is that it doesn't search the Python path and you can specify an
absolute file name.


-- 
Steven.




More information about the Python-list mailing list