我必须分析包含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'元素,但我不知道如何准确地执行该操作。你知道吗
GreenTreeSnakes有大量关于Python AST树中节点的文档。你知道吗
我不知道您是否真的要将代码解析到
ast
树中,所以我将在这里包含它。你知道吗将代码解析为树:
然后在Analyzer类中,可以从
_ast.Str
节点的s
属性获取someValue
符号。你知道吗对于
If
节点,属性为test
(_ast.Compare
)→left
(_ast.Str
)→s
(str
)。你知道吗相关问题 更多 >
编程相关推荐