python - 解析Python文件中的所有方法和类

标签 python python-2.7

我正在尝试构建一个程序,允许用户浏览到包含 python 模块的文件夹。选择文件夹后,它将列出该文件夹中的所有 python 文件以及每个模块的所有类和方法。我的问题是,有什么方法可以在不打开每个文件并解析“def”或“class”的情况下做到这一点?我注意到有一个名为 mro 的函数,它返回类的属性,但这需要我通过导入访问该类。那么有什么方法可以得到相同的结果吗?预先感谢您!

最佳答案

这就是我使用 AST 模块想到的,它正是我正在寻找的东西。

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 - 解析Python文件中的所有方法和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40406148/

相关文章:

python - 删除了 MacPorts,现在 Python 被破坏了

python - __setattr__ 如何处理类属性?

django - 如何在 virtualbox/vagrant 服务器中访问 django 网站?

python - 使用 pip 安装 MySQL-python 时,最终出现以下输出并且无法安装 MySQLdb

python - 打印功能中的 sep 和 end 有什么区别?

python - 如何自动下载网页上有下载按钮的文件?

python - pandas DateOffset 函数

python - 将 Python 日期时间转换为 firestore 时间戳格式

python - pypy编译器的使用

python - 不清楚身份验证后如何调用 API?