Importing Modules

Sam Pointon free.condiments at gmail.com
Wed Nov 2 00:37:42 EST 2005


On the second point, a combination of sys.path, os.listdir and
__import__ should do what you're after, although sifting through the
whole of sys.path and subfolders from Python, rather than the
interpreter itself, could be slow.  (And it'll be redundant as well -
__import__ will have do the same thing, though you could fix that by
using the imp module).

-Should- work, but not tested, so don't blame me if it doesn't:

import sys, os, re

def find_modules(str_pat):
    pat = re.compile(str_pat + '.py[co]?')
    init_pat = re.compile('__init__.py[co]?')
    for dir in sys.path:
        files = [n for n in os.listdir(path) if pat.search(n)]
        [__import__(name.rspit('.')) for name in files]
        for possible_dir in os.listdir(path):
            try:
                if True in [init_pat.match(n) for n in os.listdir(name
+ '/' + possible_dir):
                    find_modules(str_pat)
            except OSError: #does os.listdir raise this?
                pass




More information about the Python-list mailing list