我试图在任意 Python 代码中找到第一个函数。
执行此操作的最佳方法是什么?
这是我到目前为止尝试过的方法。
import ast
import compiler.ast
code = """\
def func1():
return 1
def func2():
return 2
"""
tree = compiler.parse(code)
print list(ast.walk(tree))
但是我遇到了一个我不明白的错误。
Traceback (most recent call last):
File "test.py", line 15, in <module>
print list(ast.walk(tree))
File "/usr/lib64/python2.7/ast.py", line 215, in walk
todo.extend(iter_child_nodes(node))
File "/usr/lib64/python2.7/ast.py", line 180, in iter_child_nodes
for name, field in iter_fields(node):
File "/usr/lib64/python2.7/ast.py", line 168, in iter_fields
for field in node._fields:
AttributeError: Module instance has no attribute '_fields'
请您参考如下方法:
使用ast.parse , 而不是 compiler.parse:
>>> import ast
>>>
>>> code = """
... def func1():
... return 1
...
... def func2():
... return 2
... """
>>>
>>> tree = ast.parse(code)
>>> [x.name for x in ast.walk(tree) if isinstance(x, ast.FunctionDef)]
['func1', 'func2']
