How to load all modules in a folder?

后端 未结 18 1646
失恋的感觉
失恋的感觉 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:16

    I know I'm updating a quite old post, and I tried using automodinit, but found out it's setup process is broken for python3. So, based on Luca's answer, I came up with a simpler answer - which might not work with .zip - to this issue, so I figured I should share it here:

    within the __init__.py module from yourpackage:

    #!/usr/bin/env python
    import os, pkgutil
    __all__ = list(module for _, module, _ in pkgutil.iter_modules([os.path.dirname(__file__)]))
    

    and within another package below yourpackage:

    from yourpackage import *
    

    Then you'll have all the modules that are placed within the package loaded, and if you write a new module, it'll be automagically imported as well. Of course, use that kind of things with care, with great powers comes great responsibilities.

提交回复
热议问题