输出python模块依赖

#!/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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值