How to load all modules in a folder?

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

    Expanding on Mihail's answer, I believe the non-hackish way (as in, not handling the file paths directly) is the following:

    1. create an empty __init__.py file under Foo/
    2. Execute
    import pkgutil
    import sys
    
    
    def load_all_modules_from_dir(dirname):
        for importer, package_name, _ in pkgutil.iter_modules([dirname]):
            full_package_name = '%s.%s' % (dirname, package_name)
            if full_package_name not in sys.modules:
                module = importer.find_module(package_name
                            ).load_module(full_package_name)
                print module
    
    
    load_all_modules_from_dir('Foo')
    

    You'll get:

    
    
    

提交回复
热议问题