在REPL的后台导入python模块

时间:2017-12-14 15:16:10

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

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

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

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

1 个答案:

答案 0 :(得分:3)

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

创建文件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())
在解释器中

加载模块。