动态加载目录中的所有模块,并将其添加到Python中的列表中(Dynamically load all modules within a directory and add it to a list in Python)
我有一个包含Python文件的目录(和子目录)。 每个文件只包含1个类。
这里是一个例子
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中做到吗? 如果可能的话,如何实现这一点有什么建议?
I have a directory (and sub directories) that contain Python files. Each file contain only 1 class.
Here an example
commands/ping.py
class Ping: def __init__(): print('works')What I want to do is something along the lines of:
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 classIs this possible to do in Python3.5? What are some suggestions on how to achieve this if it is possible?
最满意答案
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())我使用上面的代码解决了它。 如果有人想在将来也这样做,请发帖。
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())I solved it using the above code. Posting it if anyone want to do the same in the future.
更多推荐
发布评论