1 回答
TA贡献1807条经验 获得超9个赞
以下代码将遍历文件并在层次结构中创建一个对象。
import ast
import pprint
def create_py_object(node_to_traverse, current_object):
for node in node_to_traverse.body:
if isinstance(node, ast.ClassDef):
current_object.append({node.name: []})
create_py_object(node, current_object[-1:][0][node.name])
if isinstance(node, ast.FunctionDef):
current_object.append({node.name: 'func'})
file = open("TestFile.py", "r")
f = file.read()
node_to_traverse = ast.parse(f)
py_file_structure = []
create_py_object(node_to_traverse, py_file_structure)
pprint.pprint(py_file_structure)
输出 :
[{'adf': [{'message': 'func'}, {'dghe': 'func'}]},
{'A': [{'__init__': 'func'}, {'mess': 'func'}, {'B': [{'teqwtdg': 'func'}]}]}]
添加回答
举报