一些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())
在您的解释器中加载模块。