有没有办法让这个函数更智能地查找Python模块的依赖项?我在所有1900多个项目文件中运行此操作,其中一些需要1秒多的时间来处理。
看起来ModuleFinder递归地计算模块的依赖关系,但是我还没有找到任何方法让它重新使用下一个文件的信息...
ps:我使用了pathlib的2.7端口
import sys, os
from modulefinder import ModuleFinder
from pathlib import Path
def dependencies(fname, root=None):
"""Find all dependencies (i.e. imported modules) from fname without
running it.
If `root` is specified, only modules having __file__ attributes
under this root is included.
This function is quite slow..
"""
assert fname.endswith('.py')
res = set()
finder = ModuleFinder()
try:
finder.run_script(fname)
except:
return []
root = normpath(root, slash='/')
prefix = len(root) + 1 # for trailing slash
for name, mod in finder.modules.iteritems():
if name.startswith('_'):
continue
modpath = normpath(mod.__file__, slash='/')
if modpath.startswith(root):
res.add(modpath[prefix:])
return list(sorted(res))
def normpath(p, slash=None):
"""Return a canonical version of path ``p``.
"""
res = ""
if isinstance(p, Path):
p = str(p.absolute())
if p is not None:
res = os.path.normcase(os.path.normpath(os.path.abspath(p)))
if slash is None:
return res
else:
return res.replace('\\', slash)