importlib.import_模块正在忽略没有错误消息的模块

2024-06-01 00:24:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个CLI应用程序,它有各种各样的插件架构。用户可以以.py文件的形式编写新模块,将它们放到“plugin”目录中,它们将在开始时自动加载

然而,我有一个奇怪的情况,在从目录中检索文件列表并返回10个文件的列表后,当我使用importlib.import_模块循环导入它们时,只导入其中的一部分。。。 没有返回任何错误消息,而且它似乎甚至阻止了同一for循环中以前的语句:

PluginRegistry.import_modules("../../plugins")

(...)
class PluginRegistry:
    def import_modules(dir_name):
        direc = os.path.abspath(os.path.join(WORKING_DIR, dir_name))
        sys.path.append(direc)

        candidates = list(glob.iglob(direc + '**/**/*.py', recursive=True))
        print(candidates)

        modules = []
        for i, file in enumerate(candidates):
            module_name = file\
                .replace(direc + "/", "")\
                .replace("/", ".")\
                .replace(".py", '')
            print(module_name)
            modules.append(module_name)

        for module in modules:
            print(module)
            importlib.import_module(module)

            print("Imported plugin module " + module)

在标准输出上打印以下内容:

text_peaks
standard_properties
experiment_properties
tables.table_inputfiles
tables.table_errors
tables.table_full
decorators.decorator_statistics
decorators.decorator_manifests
graphs.graph_totals_count
(… more of those)

text_summary
Imported plugin module text_summary
text_peaks
Imported plugin module text_peaks
standard_properties
Imported plugin module standard_properties
experiment_properties
Imported plugin module experiment_properties
tables.table_inputfiles
Imported plugin module tables.table_inputfiles
tables.table_errors
Imported plugin module tables.table_errors
tables.table_full
Imported plugin module tables.table_full
decorators.decorator_statistics

然后它停止了。。。没有错误,什么都没有。 如果我删除那个decorator_statistics.py文件,它会进入下一个文件,但又会在那里停止

知道会出什么问题吗

更奇怪的是,这是当我以“-help”作为参数(我使用argparse)运行脚本时的行为

如果使用标准参数运行脚本,则所有导入都会正常进行。但我是这两种情况下,第一行的PluginRegistry.import_modules(…)是第一个执行的语句


Tags: 文件textnamepyimportmodulestablestable