ser*_*inc 5 python background-process python-import read-eval-print-loop
一些 python 模块,尤其是matplotlib,需要很长时间才能加载
start = datetime.datetime.now(); import numpy, pandas, matplotlib, sklearn; datetime.datetime.now() - start
Run Code Online (Sandbox Code Playgroud)
对于缓存文件需要半秒,对于非缓存文件需要几秒钟。在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)
Run Code Online (Sandbox Code Playgroud)
然后你可以使用命令启动解释器:
python -ic "exec(open(\"load_modules.py\").read(), globals())"
Run Code Online (Sandbox Code Playgroud)
或者只是运行
exec(open("load_modules.py").read(), globals())
Run Code Online (Sandbox Code Playgroud)
在你的解释器中加载模块。
| 归档时间: |
|
| 查看次数: |
2030 次 |
| 最近记录: |