当前位置: 代码迷 >> python >> 如何在Python中解析整个脚本?
  详细解决方案

如何在Python中解析整个脚本?

热度:19   发布时间:2023-07-14 09:52:10.0

我如何解析整个python脚本? 如下:

test.py:

import app

import _ast
import ast

if __name__ == "__main__":
##    as1t = compile("app.py","<string>","exec",_ast.PyCF_ONLY_AST)
    p = ast.parse("app.py")
    print(ast.dump(p))

它解析字符串“ app.py”,而不是实际的脚本。 如何实现呢? 非常感谢你!

ast.parse()需要代码文本,而不是文件名:

import ast

with open('app.py') as fp:
    code = fp.read()
    tree = ast.parse(code)
    print ast.dump(tree)