Finding a module's sub modules at runtime
Alex Martelli
aleax at mac.com
Thu Mar 29 21:58:44 EDT 2007
Joshua J. Kugler <joshua at eeinternet.com> wrote:
> On Thursday 29 March 2007 07:33, Alex Martelli wrote:
>
> > Joshua J. Kugler <joshua at eeinternet.com> wrote:
> >
> >> still be nicely portable. It just seems that since Python is gathering
> >> that information anyway, it should make it available without me having to
> >> walk the directory tree.
> >
> > Sorry, where is Python "gathering that information anyway"? Unless I'm
> > mistaken, Python by default does not walk directory trees of subpackages
> > -- what makes you think it does?
>
> Hmm...right: dynamic language, runtime binding. It would go out and find
> whether or not Module1.Module2 existed only when import was called. Sorry,
> my bad. I am assuming, however, that the help function walks the directory
> tree, or else I would not get output like this:
>
> >>> import ModTest
> >>> help(ModTest)
> Help on package ModTest:
>
> NAME
> ModTest
>
> FILE
> /usr/local/lib/python2.4/site-packages/ModTest/__init__.py
>
> PACKAGE CONTENTS
> AModule
> BModule
> CModule
>
> Thanks for the clarification.
Sure, pydoc (which help calls under the code) does that, with a nice mix
of inspect, os, and pkgutil.iter_modules calls. pkgutil.iter_modules
may in fact be most of what you need:
>>> help(pkgutil.iter_modules)
Help on function iter_modules in module pkgutil:
iter_modules(path=None, prefix='')
Yields (module_loader, name, ispkg) for all submodules on path,
or, if path is None, all top-level modules on sys.path.
'path' should be either None or a list of paths to look for
modules in.
'prefix' is a string to output on the front of every module name
on output.
You will still have to call it recursively, though, I believe.
Alex
More information about the Python-list
mailing list