Python插件结构 - 从另一个文件执行代码

时间:2018-03-22 09:31:02

标签: python methods

我们说我有一个包含主文件main.py和配置文件config.json的文件夹。

在JSON文件中,有多个条目包含不同的文件名和每个文件中的方法名称。

根据main.py的用户输入,我从config.json获取相应的文件名和方法,现在我想执行该方法。

我尝试了以下

file = reports [id]["filename"]
method = reports [id]["method"]
# which would give me: file = 'test.py' and method = 'execute'
import file
file.method()

这显然不起作用。问题是我无法知道编译期间有哪些文件。

其他开发人员会将脚本添加到特定文件夹并将其条目添加到配置文件(有点像插件)。有人在这里有解决方案吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

感谢您的投入...... importlib是您的最佳选择。我在这里使用了这个答案:

How to import a module given the full path?