【发布时间】:2013-02-21 18:50:04
【问题描述】:
我正在尝试对 Python 代码库中的类和函数依赖项进行一些分析。我的第一步是使用 Python 的 csv 模块和正则表达式创建一个用于导入 Excel 的 .csv 文件。
我所拥有的当前版本如下所示:
import re
import os
import csv
from os.path import join
class ClassParser(object):
class_expr = re.compile(r'class (.+?)(?:\((.+?)\))?:')
python_file_expr = re.compile(r'^\w+[.]py$')
def findAllClasses(self, python_file):
""" Read in a python file and return all the class names
"""
with open(python_file) as infile:
everything = infile.read()
class_names = ClassParser.class_expr.findall(everything)
return class_names
def findAllPythonFiles(self, directory):
""" Find all the python files starting from a top level directory
"""
python_files = []
for root, dirs, files in os.walk(directory):
for file in files:
if ClassParser.python_file_expr.match(file):
python_files.append(join(root,file))
return python_files
def parse(self, directory, output_directory="classes.csv"):
""" Parse the directory and spit out a csv file
"""
with open(output_directory,'w') as csv_file:
writer = csv.writer(csv_file)
python_files = self.findAllPythonFiles(directory)
for file in python_files:
classes = self.findAllClasses(file)
for classname in classes:
writer.writerow([classname[0], classname[1], file])
if __name__=="__main__":
parser = ClassParser()
parser.parse("/path/to/my/project/main/directory")
这会生成格式为 .csv 的输出:
class name, inherited classes (also comma separated), file
class name, inherited classes (also comma separated), file
... etc. ...
除了类名之外,我还想开始解析函数声明和定义。我的问题:有没有更好的方法来获取类名、继承类名、函数名、参数名等?
注意:我考虑过使用 Python ast 模块,但我没有使用它的经验,也不知道如何使用它来获取所需的信息,或者它是否可以做到这一点。
编辑:响应 Martin Thurau 提供更多信息的要求 - 我试图解决此问题的原因是因为我继承了一个相当冗长(100k+ 行)的项目,该项目没有可辨别的其模块、类和函数的结构;它们都作为文件集合存在于单个源目录中。
一些源文件包含几十个相切相关的类,并且有 10k+ 行长,这使得它们难以维护。我开始对使用The Hitchhiker's Guide to Packaging 作为基础将每个类打包成一个更有凝聚力的结构的相对难度进行分析。对于该分析,我关心的部分内容是一个类与其文件中的其他类的交织程度,以及特定类依赖于哪些导入或继承的类。
【问题讨论】:
-
@Fredrik 我快速浏览了文档。
inspect似乎只适用于实时(运行时)代码。我错了吗?我认为我需要使用静态分析,因为并非每个函数/类都将用于任何给定的代码运行。 -
pyflakesstatic code checker用的是AST,或许可以拿来举例? -
无论您实际尝试做什么:请记住,您可以在运行时创建、加载和实例化类,因此无法在 100% 的时间内获得 100% 正确。
-
@MartinThurau 感谢您抽出宝贵时间提供反馈。我重新阅读了这个问题,并意识到我没有很好地说明我的目的,所以我添加了关于我实际上想要做什么的新信息。
标签: python regex python-2.6