Python 同一文件名的多个导入

Python 同一文件名的多个导入,python,plugins,import,system,Python,Plugins,Import,System,我正在尝试创建一个插件系统,我有一个将所有模块导入阵列的函数 插件布局: pluginsDir/ 插件目录/聊天 pluginsDir/chat/main.py 这是查找和导入插件的功能: if os.path.exists(pluginsDir): for path, dirArray, fileArray in os.walk(pluginsDir): for fileName in fileArray: if fileName == &quo

我正在尝试创建一个插件系统,我有一个将所有模块导入阵列的函数

插件布局:

pluginsDir/

插件目录/聊天

pluginsDir/chat/main.py

这是查找和导入插件的功能:

if os.path.exists(pluginsDir):
    for path, dirArray, fileArray in os.walk(pluginsDir):
        for fileName in fileArray:
            if fileName == "main.py":
            sys.path.append(path)
            try:
                plugins.append(__import__("main"))
            except:
                print 'Could not import plugin, "'+path+'": plugin contains errors or is not a real plugin.'
这是好的,如果我只有一个插件,但当我有多个插件时,它会继续导入它检测到的第一个插件

插件布局:

pluginsDir/

插件目录/聊天

pluginsDir/chat/main.py

pluginsDir/build

pluginsDir/build/main.py

我已经尝试在try语句之后添加
sys.path.remove(path)
,但是在我已经导入模块之后,它没有删除路径


如何才能正确导入插件?

您的内部for循环没有缩进,我不明白您的代码为什么会运行。修复缩进可能会解决这个问题。

您的内部for循环没有缩进,我不明白为什么您的代码会运行。修复缩进可能会解决问题。

Python模块系统只是处理名称空间的一种非常酷的方式。将几个具有相同名称的模块导入到当前名称空间将使其混乱

不需要遍历pluginsDir并导入每个文件,Python将为您完成这项工作(从pluginsDir import*)。如果main.py仅执行初始化stuf,则可以将代码移动到
pluginsDir/chat/\uuuu init\uuuuu.py


导入pluginsDir引用“pluginsDir.chat”之类的插件被认为是更好的做法。

Python模块系统只是处理名称空间的一种非常酷的方式。将几个具有相同名称的模块导入到当前名称空间将使其混乱

不需要遍历pluginsDir并导入每个文件,Python将为您完成这项工作(从pluginsDir import*)。如果main.py仅执行初始化stuf,则可以将代码移动到
pluginsDir/chat/\uuuu init\uuuuu.py

导入pluginsDir引用“pluginsDir.chat”之类的插件被认为是更好的做法。

sys.path.append(path)
将插件文件夹附加到
sys.path
端。由于Python从前到后搜索
sys.path
中的文件夹,因此将无法找到附加到列表末尾的路径,因为前面在
sys.path
中指定的文件夹中的任何main.py模块基本上将隐藏列表末尾文件夹中的模块。相反,您可以使用
sys.path.insert(0,path)
将新路径添加到列表的前面

您应该寻找一种更好地构建插件的方法

plugindir/
    __init__.py
    plugin1/
        __init__.py
    plugin2/
        __init__.py
使用Python包,脚本中的循环可以通过以下方式轻松实现:

sys.path.insert(0, path_to_plugindir)
for folder in dirArray:
    __import__(folder)
sys.path.append(path)
将插件文件夹附加到
sys.path
末尾。由于Python从前到后搜索
sys.path
中的文件夹,因此将无法找到附加到列表末尾的路径,因为前面在
sys.path
中指定的文件夹中的任何main.py模块基本上将隐藏列表末尾文件夹中的模块。相反,您可以使用
sys.path.insert(0,path)
将新路径添加到列表的前面

您应该寻找一种更好地构建插件的方法

plugindir/
    __init__.py
    plugin1/
        __init__.py
    plugin2/
        __init__.py
使用Python包,脚本中的循环可以通过以下方式轻松实现:

sys.path.insert(0, path_to_plugindir)
for folder in dirArray:
    __import__(folder)

这是因为我修改了我的代码,使其在这里更可读,但最终去掉了一些缩进。这是因为我修改了我的代码,使其在这里更可读,但最终去掉了一些缩进。我需要用我的方法来做这件事,因为插件是动态的,而不是静态的,所以如果添加了插件,我的脚本无法使用此方法检测到它。您可以使用内置函数重新加载。我需要用我的方法来做这件事,因为插件是动态的,而不是静态的,所以如果添加了插件,我的脚本将不会用这个方法检测到它。你可以使用内置函数重载。