标签:ted spec index 加载 load 目录 tree none ade
($是命令行提示符)
$ #目录结构
$ tree
.
├── a.py
└── impt.py
0 directories, 2 files
# impt.py
import sys
import importlib
from importlib.util import LazyLoader
for i, mp in enumerate(sys.meta_path):
if str(mp) == "<class ‘_frozen_importlib_external.PathFinder‘>":
index = i
path_finder = mp
continue
class LazyPathFinder(object):
def find_spec(self, fullname, path, target=None):
spec = path_finder.find_spec(fullname, path, target=target)
if spec is not None:
spec.loader = LazyLoader(spec.loader)
return spec
sys.meta_path[index] = LazyPathFinder()
import os
import a
print(‘a lazy imported‘)
print(a.b)
# a.py
print(‘exec a.py‘)
b = 2
$ python impt.py
a lazy imported
exec a.py
2
??,大功告成!a模块懒加载了。
标签:ted spec index 加载 load 目录 tree none ade
原文地址:https://www.cnblogs.com/lyg-blog/p/14806886.html