1

我正在使用 AST 库来提取这样一个文件的所有细节,

import ast
file = open("TestFile.py", "r")
f = file.read()
p = ast.parse(f)
classFunc = [node.name for node in ast.walk(p) if isinstance(node, ast.ClassDef) or isinstance(node, ast.FunctionDef)]
print classFunc

这给了我一个输出,

['adf', 'A', 'message', 'dghe', '__init__', 'mess', 'B', 'teqwtdg']

这里'adf'和'A'是主类,'message'和'dghe'是'adf'下的函数,' init '和'mess'是A下的函数,'B'是'下的一个类A'和'teqwtdg'是'B'下的一个函数。

所以,现在我的任务是编写一个 python 文件,在其中创建类实例并调用这些函数(这些来自未知文件)。我想安排这个列表,以便我可以很容易地知道哪些是主类,哪些是子类以及哪个函数属于哪个类。我怎样才能做到这一点?

4

1 回答 1

1

以下代码将遍历文件并在层次结构中创建一个对象。

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'}]}]}]
于 2020-02-13T08:00:54.350 回答