<p dir="ltr"><br>
On Jul 30, 2014 4:37 AM, "Robert Kern" <<a href="mailto:robert.kern@gmail.com">robert.kern@gmail.com</a>> wrote:<br>
><br>
> On 2014-07-30 09:46, Peter Otten wrote:<br>
>><br>
>> Steven D'Aprano wrote:<br>
>><br>
>>> I'm looking for a programmatic way to get a list of all Python modules<br>
>>> and packages. Not just those already imported, but all those which<br>
>>> *could* be imported.<br>
>>><br>
>>> I have a quick-and-dirty function which half does the job:<br>
>>><br>
>>><br>
>>> def get_modules():<br>
>>>      extensions = ('.py', '.pyc', '.pyo', '.so', '.dll')<br>
>>>      matches = set()<br>
>>>      for location in sys.path:<br>
>>>          if location == '': location = '.'<br>
>>>          if os.path.isdir(location):<br>
>>>              for name in os.listdir(location):<br>
>>>                  base, ext = os.path.splitext(name)<br>
>>>                  if ext in extensions:<br>
>>>                      matches.add(base)<br>
>>>      return sorted(matches)<br>
>>><br>
>>><br>
>>><br>
>>> but I know it's wrong (it doesn't handle packages correctly, or zip<br>
>>> files, doesn't follow .pth files, has a very naive understanding of cross-<br>
>>> platform issues, fails to include built-in modules that don't live in the<br>
>>> file system, and probably more).<br>
>>><br>
>>> Is this problem already solved? Can anyone make any suggestions?<br>
>><br>
>><br>
>> $ python3 -m pydoc -b<br>
>><br>
>> shows a page with modules that I think is more complete than what you have.<br>
>> A quick glance at the implementation suggests that the hard work is done by<br>
>><br>
>> pkgutil.iter_modules()<br>
><br>
><br>
> There are two niggles to this answer: it omits builtin modules, but those are easily discovered through sys.builtin_module_names. It can also include spurious script .py files that cannot be imported because their names are not Python identifiers: e.g. check-newconfigs.py. Those are easy to filter out, fortunately.</p>

<p dir="ltr">It will also omit any modules provided by a custom module finder that doesn't implement iter_modules, which is not a required part of the interface.<br>
</p>