How to find all child modules in Python?

后端 未结 6 1262
走了就别回头了
走了就别回头了 2021-02-19 11:46

While it is fairly trivial in Python to import a \"child\" module into another module and list its attributes, it becomes slightly more difficult when you want to import all

6条回答
  •  南笙
    南笙 (楼主)
    2021-02-19 12:25

    pkgutil.walk_packages() seems to be the right way to do this. Here's how I found a list of the available modules, and then imported one of them:

    $ mkdir foo
    $ touch foo/__init__.py
    $ touch foo/bar.py
    $ python
    Python 3.8.2 (default, Jul 16 2020, 14:00:26) 
    [GCC 9.3.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import foo
    >>> from pkgutil import walk_packages
    >>> list(walk_packages(foo.__path__))
    [ModuleInfo(module_finder=FileFinder('/home/don/git/zero-play/zero_play/foo'), name='bar', ispkg=False)]
    >>> from importlib import import_module
    >>> bar = import_module('foo.bar')
    
    

提交回复
热议问题