Frage

How can I parse the whole python script? as the following:

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))

It parses the String "app.py" instead of the actual script. How to realize it? Thank you very much!

War es hilfreich?

Lösung

ast.parse() expects the code text, not the file name:

import ast

with open('app.py') as fp:
    code = fp.read()
    tree = ast.parse(code)
    print ast.dump(tree)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top