动态加载目录中的所有模块,并将其添加到Python中的列表中(Dynamically load all modules within a directory and add it to a list

编程入门 行业动态 更新时间:2024-10-26 09:33:52
动态加载目录中的所有模块,并将其添加到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 class

Is 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.

更多推荐

本文发布于:2023-08-02 15:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1378344.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模块   加载   动态   列表中   目录中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!