动态加载目录中的所有模块,并将其添加到Python中的列表中

时间:2017-08-07 15:23:14

标签: python-3.5

我有一个包含Python文件的目录(和子目录)。每个文件只包含一个类。

这是一个例子

commands/ping.py

class Ping:
    def __init__():
        print('works')

我想要做的是:

commands = []

def load_commands():
    for name in os.listdir('/commands'):
        module = import name
        for key, value in module:
            print(key, value) #-> "Ping", ClassObject
            if isClass(value):
                commands.append(Value()) #where value is the class

这可以在Python3.5中完成吗?如果有可能,如何实现这一目标有哪些建议?

1 个答案:

答案 0 :(得分:0)

import inspect
import importlib

def load_commands(self):
    for directory in os.listdir('{0}/commands/'.format(self._config['root_directory'])):
        if (directory != "__init__.py" and directory != "__pycache__"):
            for file in os.listdir('{0}/commands/{1}'.format(self._config['root_directory'], directory)):
                if (file != "__init__.py" and file != "__pycache__"):
                    path = "commands.{0}.{1}".format(directory, file[:-3])
                    module = inspect.getmembers(importlib.import_module(path))

                    for key, value in module:
                        if (inspect.isclass(value) and issubclass(value, Command) and not key == "Command"):
                            self._commander.add(value())

我使用上面的代码解决了它。如果有人想在将来做同样的事情,请张贴。