问题
Let's say I've already imported a python module in the interpreter. How can I get the abstract syntax tree of the imported module (and any functions and classes within it) within the interpreter? I don't want to have to re-parse the source files. Thanks!
回答1:
Maybe you find some inspiration in this recipe:
- http://code.activestate.com/recipes/533146-ast-pretty-printer/
A function that outputs a human-readable version of a Python AST.
Or use compiler
combined with inspect
(which, of course, still uses the source):
>>> import compiler, inspect
>>> import re # for testing
>>> compiler.parse(inspect.getsource(re))
Module('Support for regular expressions (RE). \n\nThis module provides ...
回答2:
There doesn't seem to be a way to get an AST except from source code. If you explain why you don't want to re-parse the source files, maybe we can help with that.
来源:https://stackoverflow.com/questions/4812144/python-get-the-abstract-syntax-tree-of-imported-function