Cannot import a module from a variable

Cameron Walsh cameron.walsh at gmail.com
Wed Oct 18 21:51:35 EDT 2006


Hi,

This has actually been answered in a previous post ("user modules"
started by myself), for which I was very grateful.  I have since
expanded on their solutions to create the following code, of which parts
or all may be useful.  You'll probably be most interested in the last
part of the code, from "# Now we actually import the modules" onwards.

>>> import os
>>> import glob
>>> # import_extension_modules(directory)
>>> # Imports all the modules in the sub-directory "directory"
>>> # "directory" MUST be a single word and a sub-directory of that
>>> # name MUST exist.
>>> # Returns then as a dictionary of {"module_name":module}
>>> # This works for both .py (uncompiled modules)
>>> # and .pyc (compiled modules where the source code is not given)
>>> # TODO: Fix limitations above, clean up code.
>>> #
>>> def import_extension_modules(directory):
    previous_directory = os.getcwd()
    try:
        os.chdir(directory)
        uncompiled_files = glob.glob("*.py")
        compiled_files = glob.glob("*.pyc")
        all_files = []
        modules = {}
        for filename in uncompiled_files:
            all_files.append(filename[0:-3]) # Strip off the ".py"
        for filename in compiled_files:
            # Add any pre-compiled modules without source code.
            filename = filename[0:-4] # Strip off the ".pyc"
            if filename not in all_files:
                all_files.append(filename)
        if "__init__" in all_files:
            # Remove any occurrences of __init__ since it does
            # not make sense to import it.
            all_files.remove("__init__")
        # Now we actually import the modules
        for module_name in all_files:
            # The last parameter must not be empty since we are using
            # import blah.blah
            # format because we want modules not packages.
            # see 'help(__import__)' for details.
            module = __import__("%s.%s" %(directory,module_name), None,
None,["some string to make this a non-empty list"])
            modules[module.__name__] = module
        return modules
    finally:
        os.chdir(previous_directory)

>>> user_modules = import_extension_modules("user_modules")
>>> user_modules
{'user_modules.funky_module': <module 'user_modules.funky_module' from
'C:\Projects\module_import_tester\src\user_modules\funky_module.pyc'>}

Woah, that actually works?  Having the "finally" after the "return"?
That could make some things easier, and some things harder...

Hope that helps,

Cameron.



More information about the Python-list mailing list