Python 3.x Python Libcst:无法从visitor类中的节点生成代码
我正在寻找一种从访问者中的节点获取代码的方法。 例如: 在上面的代码中,我想得到节点的代码(即threshold=1)。但libcst似乎没有提供这种支持。我进一步环顾四周,找到了_节点(节点:libcst._nodes.base.CSTNode)的函数名Python 3.x Python Libcst:无法从visitor类中的节点生成代码,python-3.x,abstract-syntax-tree,libcst,Python 3.x,Abstract Syntax Tree,Libcst,我正在寻找一种从访问者中的节点获取代码的方法。 例如: 在上面的代码中,我想得到节点的代码(即threshold=1)。但libcst似乎没有提供这种支持。我进一步环顾四周,找到了_节点(节点:libcst._nodes.base.CSTNode)的函数名code_→ str属于模块。但是我没有找到足够的帮助来在代码中使用它 期待您的帮助。 提前谢谢 花了一段时间后,我想出了解决问题的办法。这是代码 代码: import libcst as cst code_example = "&
code_→ str
属于模块。但是我没有找到足够的帮助来在代码中使用它
期待您的帮助。
提前谢谢 花了一段时间后,我想出了解决问题的办法。这是代码 代码:
import libcst as cst
code_example = """
from ast import parse
threshold = 1
print(threshold)
"""
class CodeVisitor(cst.CSTVisitor):
def visit_Assign(self, node: cst.Assign) -> bool:
print("--> NODE TREE: \n{}".format(node))
print("--> CODE LINE FROM NODE TREE: \n{}".format(cst.parse_module("").code_for_node(node)))
return True
demo = cst.parse_module(code_example)
_ = demo.visit(CodeVisitor())
--> NODE TREE:
Assign(
targets=[
AssignTarget(
target=Name(
value='threshold',
lpar=[],
rpar=[],
),
whitespace_before_equal=SimpleWhitespace(
value=' ',
),
whitespace_after_equal=SimpleWhitespace(
value=' ',
),
),
],
value=Integer(
value='1',
lpar=[],
rpar=[],
),
semicolon=MaybeSentinel.DEFAULT,
)
--> CODE LINE FROM NODE TREE:
threshold = 1
输出:
import libcst as cst
code_example = """
from ast import parse
threshold = 1
print(threshold)
"""
class CodeVisitor(cst.CSTVisitor):
def visit_Assign(self, node: cst.Assign) -> bool:
print("--> NODE TREE: \n{}".format(node))
print("--> CODE LINE FROM NODE TREE: \n{}".format(cst.parse_module("").code_for_node(node)))
return True
demo = cst.parse_module(code_example)
_ = demo.visit(CodeVisitor())
--> NODE TREE:
Assign(
targets=[
AssignTarget(
target=Name(
value='threshold',
lpar=[],
rpar=[],
),
whitespace_before_equal=SimpleWhitespace(
value=' ',
),
whitespace_after_equal=SimpleWhitespace(
value=' ',
),
),
],
value=Integer(
value='1',
lpar=[],
rpar=[],
),
semicolon=MaybeSentinel.DEFAULT,
)
--> CODE LINE FROM NODE TREE:
threshold = 1