python - 以编程方式导入适用于 Windows,但不适用于 Linux

标签 python plugins import

所以我有一个目录树如下:

pluginlist.py
plugins/
    __init__.py
    plugin1.py
    plugin2.py
    ...

并且想要从每个plugin1、plugin2等连接一个名称相似的字典。

我这样做的方式如下(来自pluginlist.py):

import os

pluginFolderName = "plugins"
pluginFlag = "##&plugin&##"

commands = {}

os.chdir(os.path.abspath(pluginFolderName))

for file in os.listdir(os.getcwd()):
    if os.path.isfile(file) and os.path.splitext(file)[1] == ".py":
        fileo = open(file, 'r')
        firstline = fileo.readline()
        if firstline == "##&plugin&##\n":
            plugin_mod = __import__("plugins.%s" % os.path.splitext(file)[0])
            import_command = "plugin_commands = plugin_mod.%s" %     os.path.splitext(file)[0]
            exec import_command
            commands = dict(commands.items() + plugin_commands.commands.items())
print commands

(那里的打印命令用于测试目的)

在 Windows 上运行它会给出正确的命令字典,但在 Linux(Ubuntu Server)上运行它会给出一个空字典。

最佳答案

尝试:

for file in os.listdir(os.getcwd()):
    basename, ext = os.path.splitext(file)
    if os.path.isfile(file) and ext == ".py":
        with open(file, 'r') as fileo:
            firstline = fileo.readline()
            if firstline.startswith("##&plugin&##"):
                plugin_mod = __import__("plugins.%s" % basename, fromlist = [True])
                plugin_commands = getattr(plugin_mod, basename)
                commands.update(plugin_commands.commands)

当调用__import__('A.B')时,会返回包A。 当您调用 __import__('A.B', fromlist = [True]) 时,将返回模块 B。在我看来你想要B。因此,在 Windows 和 Linux 上,您应该需要将 fromlist 设置为某个非空列表。

关于python - 以编程方式导入适用于 Windows,但不适用于 Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10004265/

相关文章:

javascript - 在小书签中使用@import 和@font-face(适用于 Chrome,但不适用于 Firefox)

python - 使用类方法作为 GSL QAGS 的被积函数

python - 如何增加/减少 x 和 y 刻度标签的字体大小

plugins - 如何为 Confluence 创建导出插件

Eclipse .metadata\.plugins 磁盘空间

mysql - 从 Excel 导入到 SQL,并有条件检查重复项

c# - 将 C++ .lib 和 .h 文件导入 C# 项目?

python - 为属性提供自定义 __str__ 表示

python - 为什么深度学习 Keras 上的准确率总是 0.00%,损失很高

plugins - PyCharm UML 编辑器不存在?