如何使用python ast模块分析ifn语句

2024-09-27 00:13:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须分析包含if语句的python代码,并找到ast模块:https://docs.python.org/3.8/library/ast.html 不知何故,这些文档并非一目了然。 我在这里找到了一个例子:https://www.mattlayman.com/blog/2018/decipher-python-ast/ 使用最后一个节点helper类,但我正在琢磨如何采用这个示例来获得if语句的细节。你知道吗

要分析的代码:

toggleSwitch = False

# check for someValue in the key-value store
if 'someValue' in context['someKey']:
    toggleSwitch = True

分析仪代码:

class Analyzer(ast.NodeVisitor):
    def visit_If(self, node):
        print("If:",node.test.left)
        self.stats["if"].append(node.body)
        self.generic_visit(node)

我希望访问visit\u If函数中节点的某种属性中的'someValue'元素,但我不知道如何准确地执行该操作。你知道吗


Tags: 模块代码inhttpsselfnodedocsif
1条回答
网友
1楼 · 发布于 2024-09-27 00:13:44

GreenTreeSnakes有大量关于Python AST树中节点的文档。你知道吗

我不知道您是否真的要将代码解析到ast树中,所以我将在这里包含它。你知道吗

将代码解析为树:

code = '''toggleSwitch = False

# check for someValue in the key-value store
if 'someValue' in context['someKey']:
    toggleSwitch = True'''

import ast
tree = ast.parse(code)

然后在Analyzer类中,可以从_ast.Str节点的s属性获取someValue符号。你知道吗

class Analyzer(ast.NodeVisitor):
    def __init__(self):
        self.stats = {'if': []}

    def visit_If(self, node):
        # Add the "s" attribute access here
        print("If:", node.test.left.s)
        self.stats["if"].append(node.body)
        self.generic_visit(node)

    def report(self):
        pprint(self.stats)

>>> a = Analyzer()
>>> a.visit(tree)
If: someValue

对于If节点,属性为test_ast.Compare)→left_ast.Str)→sstr)。你知道吗

相关问题 更多 >

    热门问题