解析所有方法和类的python文件 [英] Parsing python file for all methods and classes
问题描述
我正在尝试构建一个程序,该程序允许用户浏览到包含 python 模块的文件夹.选择文件夹后,它将列出该文件夹中的所有 python 文件以及每个模块的所有类和方法.我的问题是,有没有什么办法可以在不打开每个文件并解析def"或class"的情况下做到这一点?我注意到有一个名为 mro 的函数,它返回一个类的属性,但这需要我通过导入访问该类.那么有什么办法可以得到相同的结果吗?提前致谢!
I am trying to build a program which allows the user to browse to a folder which contains python modules. Once the folder has been selected it will list all python files within that folder as well as all the classes and methods for each module. My question is, are there any way I can do this without opening each file and parsing for "def" or "class"? I noticed that there's a function called mro which returns the attribute of a class but that requires me to have access to that class through an import. So is there any way I can get the same result? Thank you in advance!
推荐答案
这是我想出的使用 AST 模块的方法,它正是我想要的.
This is what I came up with using the AST module, it has exactly what I was looking for.
def fillClassList(file):
classList = []
className = None
mehotdName = None
fileName = "C:\Transcriber\Framework\ctetest\RegressionTest\GeneralTest\\" + file
fileObject = open(fileName,"r")
text = fileObject.read()
p = ast.parse(text)
node = ast.NodeVisitor()
for node in ast.walk(p):
if isinstance(node, ast.FunctionDef) or isinstance(node, ast.ClassDef):
if isinstance(node, ast.ClassDef):
className = node.name
else:
methodName = node.name
if className != None and methodName != None:
subList = (methodName , className)
classList.append(subList)
return classList
这篇关于解析所有方法和类的python文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!