【问题标题】:Import python modules in the background in REPL在 REPL 的后台导入 python 模块
【发布时间】:2017-12-14 15:16:09
【问题描述】:

一些 python 模块,尤其是 matplotlib,需要很长时间才能加载

start = datetime.datetime.now(); import numpy, pandas, matplotlib, sklearn; datetime.datetime.now() - start

缓存文件需要半秒钟,non-cached files 需要几秒钟。在 Python 解释器中时,有没有办法在后台加载这些模块?

【问题讨论】:

  • 在我 5½ 岁的 Macbook Pro 上使用了 0:00:00.645208。这会扰乱您的工作流程吗?
  • @RyanSandridge:如果它发生第 100 次,它会发生(对我来说类似的价值)。更重要的是:如果文件没有被缓存,可能需要几秒钟。所以要么输入它并有下一个>>>提示可用,要么觉得有点无聊,等待,也许切换任务,...

标签: python python-import background-process read-eval-print-loop


【解决方案1】:

您可以在单独的线程中导入模块。这是解决方案。

创建文件load_modules.py:

from concurrent.futures import ThreadPoolExecutor
import importlib
import sys

modules_to_load = ['numpy', 'pandas', 'matplotlib']


def do_import(module_name):
    thismodule = sys.modules[__name__]

    module = importlib.import_module(module_name)
    setattr(thismodule, module_name, module)
    print(module_name, 'imported')


executor = ThreadPoolExecutor()
for module_name in modules_to_load:
    executor.submit(do_import, module_name)

然后你可以用命令启动解释器:

python -ic "exec(open(\"load_modules.py\").read(), globals())"

或者直接跑

exec(open("load_modules.py").read(), globals())

在您的解释器中加载模块。

【讨论】:

  • 谢谢。这怎么可以实现为函数bg_load(module_name)
猜你喜欢
  • 1970-01-01
  • 2020-12-03
  • 2019-07-14
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多