我正在尝试在任意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'
答案 0 :(得分:5)
使用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']
答案 1 :(得分:1)
怎么样,如果有效,请告诉我:
import ast
import compiler.ast
code = """\
def func1():
return 1
def func2():
return 2
"""
n = compiler.parse(code).getChildNodes()
print n[0].nodes[0].name