Getting a list of all modules
python.leojay at gmail.com
Wed Jul 30 15:22:18 CEST 2014
On Wed, Jul 30, 2014 at 3:43 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> I'm looking for a programmatic way to get a list of all Python modules
> and packages. Not just those already imported, but all those which
> *could* be imported.
If you don't actually import it, how can you know it could be imported?
Not all .so files are valid python modules.
Not all .py files could be imported by all python interpreters.
> I have a quick-and-dirty function which half does the job:
> def get_modules():
> extensions = ('.py', '.pyc', '.pyo', '.so', '.dll')
> matches = set()
> for location in sys.path:
> if location == '': location = '.'
> if os.path.isdir(location):
> for name in os.listdir(location):
> base, ext = os.path.splitext(name)
> if ext in extensions:
> return sorted(matches)
> but I know it's wrong (it doesn't handle packages correctly, or zip
> files, doesn't follow .pth files, has a very naive understanding of cross-
> platform issues, fails to include built-in modules that don't live in the
> file system, and probably more).
> Is this problem already solved? Can anyone make any suggestions?
More information about the Python-list