How to load all modules in a folder?

后端 未结 18 1926
失恋的感觉
失恋的感觉 2020-11-22 05:37

Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:

/Foo
    bar.py
    spam.py
    eggs.py         


        
18条回答
  •  故里飘歌
    2020-11-22 06:15

    Just import them by importlib and add them to __all__ (add action is optional) in recurse in the __init__.py of package.

    /Foo
        bar.py
        spam.py
        eggs.py
        __init__.py
    
    # __init__.py
    import os
    import importlib
    pyfile_extes = ['py', ]
    __all__ = [importlib.import_module('.%s' % filename, __package__) for filename in [os.path.splitext(i)[0] for i in os.listdir(os.path.dirname(__file__)) if os.path.splitext(i)[1] in pyfile_extes] if not filename.startswith('__')]
    del os, importlib, pyfile_extes
    

提交回复
热议问题