【问题标题】:Importing modules from file path very slow Is there any solution for this?从文件路径导入模块非常慢有什么解决方案吗?
【发布时间】:2019-02-21 18:40:56
【问题描述】:

我有一个应该以动态方式自动导入的模块列表。 这是我的代码中的一个 sn-p:

for m in modules_to_import:
    module_name = dirname(__file__)+ "/" +m
    spec = importlib.util.spec_from_file_location("package", module_name)
    imported_module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(imported_module)

我测量了时间,每次导入后它变得越来越慢。是否有一些解决方案或为什么它会变慢?非常感谢!

【问题讨论】:

  • 您找到解决此问题的方法了吗?我有大约 20 个模块要导入,我的系统和 Google Colab 大约需要 1 小时!
  • 不知何故解决了。不知道又如何。但是1h肯定太长了。我有超过 100 个模块,而且肯定用了不到一个小时。
  • 嗯,有趣的是我一个月前做了同样的程序,而且速度很快。但现在它是如此缓慢。有疑问,您为什么使用importlib.import_module(item) 而不是您的脚本?有什么区别吗?

标签: python-3.x reflection python-importlib


【解决方案1】:

我没有计时,但你为什么不简化你的代码。查看您的代码,您想要导入与该文件位于同一目录中的模块。默认情况下,当您导入一个模块时,它首先要查找的位置。

首先让我们在同一个目录中创建一些要导入的文件:

First.py

def display_first():
    print("I'm first")

Second.py

def display_second():
    print("I'm second")

Third.py

def display_third():
    print("I'm third")

因此,一种方法是将您的模块放在一个 dict 中,以便以后使用。我在这里使用字典理解来构建该字典:

Solution1.py

import importlib

modules_to_import = ["First", "Second", "Third"]

modules_imported = {x: importlib.import_module(x) for x in modules_to_import}

modules_imported["First"].display_first()
modules_imported["Second"].display_second()
modules_imported["Third"].display_third()

或者,如果您真的想使用点分符号来访问模块的内容,您可以使用named tuple 来提供帮助:

Solution2.py

import importlib
import collections

modules_to_import = ["First", "Second", "Third"]

modules_imported = collections.namedtuple("imported_modules", modules_to_import)

for next_module in modules_to_import:
    setattr(modules_imported, next_module, importlib.import_module(next_module))

modules_imported.First.display_first()
modules_imported.Second.display_second()
modules_imported.Third.display_third()

【讨论】:

  • 我的问题是每次调用 importlib.import_module(x) 后它都会变慢。实际上什么都试过了。现在解决方案真的很丑陋,涉及打开一个子进程并使用该模块做一些事情。似乎是 importlib 中的错误/问题。
  • 你要导入多少个模块?这些模块是否有可能导入其他需要更多时间的模块?你是怎么计时的?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-11
  • 1970-01-01
  • 2016-09-08
  • 2021-06-23
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
相关资源
最近更新 更多