Python: import every module from a folder?

后端 未结 3 751
闹比i
闹比i 2021-01-01 00:28

What would be the best (read: cleanest) way to tell Python to import all modules from some folder?

I want to allow people to put their \"mods\" (modules) in a folder

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 01:02

    If transforming the folder itself in a module, through the use of a __init__.py file and using from import * suits you, you can iterate over the folder contents with "os.listdir" or "glob.glob", and import each file ending in ".py" with the __import__ built-in function:

    import os
    for name in os.listdir("plugins"):
        if name.endswith(".py"):
              #strip the extension
             module = name[:-3]
             # set the module name in the current global name space:
             globals()[module] = __import__(os.path.join("plugins", name)
    

    The benefit of this approach is: it allows you to dynamically pass the module names to __import__ - while the ìmport statement needs the module names to be hardcoded, and it allows you to check other things about the files - maybe size, or if they import certain required modules, before importing them.

提交回复
热议问题