How to load all modules in a folder?

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

    I got tired of this problem myself, so I wrote a package called automodinit to fix it. You can get it from http://pypi.python.org/pypi/automodinit/.

    Usage is like this:

    1. Include the automodinit package into your setup.py dependencies.
    2. Replace all __init__.py files like this:
    __all__ = ["I will get rewritten"]
    # Don't modify the line above, or this line!
    import automodinit
    automodinit.automodinit(__name__, __file__, globals())
    del automodinit
    # Anything else you want can go after here, it won't get modified.
    

    That's it! From now on importing a module will set __all__ to a list of .py[co] files in the module and will also import each of those files as though you had typed:

    for x in __all__: import x
    

    Therefore the effect of "from M import *" matches exactly "import M".

    automodinit is happy running from inside ZIP archives and is therefore ZIP safe.

    Niall

提交回复
热议问题