45fan.com - 路饭网

搜索: 您的位置主页 > 电脑频道 > 编程代码 > 阅读资讯:如何实现分析并输出Python代码依赖的库?

如何实现分析并输出Python代码依赖的库?

2015-09-02 15:28:49 来源:www.45fan.com 【

如何实现分析并输出Python代码依赖的库?

用法:
分析一个脚本的依赖: analysis_dependency.py script1.py
递归分析依赖: analysis_dependency.py script1.py -r

#!/usr/bin/env python
# encoding: utf-8
# source: https://github.com/MrLYC/ycyc/blob/dev/tools/analysis_dependency.py

import ast
import importlib
import inspect


class Analysis(ast.NodeTransformer):
 def __init__(self, paths, recursion):
 self.modules = list()
 self.paths = list(paths)
 self.recursion = recursion

 def add_module(self, module):
 if module and module not in self.modules:
self.modules.append(module)
 if self.recursion:
try:
 path = inspect.getsourcefile(importlib.import_module(module))
 if path:
self.paths.append(path)
except:
pass

 def visit_Import(self, node):
 for i in node.names:
self.add_module(i.name)

 def visit_ImportFrom(self, node):
self.add_module(node.module)

 def analysis(self):
 for p in self.paths:
try:
 with open(p,"rt") as fp:
 self.visit(ast.parse(fp.read(), p))
except:
pass
 return tuple(self.modules)

if __name__ =="__main__":
 import argparse

 parser = argparse.ArgumentParser()
 parser.add_argument("paths", nargs="+")
 parser.add_argument("-r","--recursion", action="store_true", default=False)
 args = parser.parse_args()

 analysisor = Analysis(args.paths, args.recursion)
 for m in analysisor.analysis():
 print m

本文地址:http://www.45fan.com/bcdm/19739.html
Tags: python 代码 输出
编辑:路饭网
推广内容
推荐阅读
热门推荐
推荐文章
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部