How to find all child modules in Python?

后端 未结 6 1611
走了就别回头了
走了就别回头了 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

    You can try globbing the directory:

    import os
    import glob
    
    modules = glob.glob(os.path.join('/some/path/to/modules', '*.py'))
    

    Then you can try importing them:

    checked_modules
    for module in modules:
        try:
            __import__(module, globals(), locals()) # returns module object
        except ImportError:
            pass
        else:
            checked_modules.append(module)
    

提交回复
热议问题