在 REPL 后台导入 python 个模块

Import python modules in the background in REPL

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

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

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

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

创建文件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())

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