當將 python AST 決議器模塊與包含多行字串的腳本結合使用時,這些多行字串總是被簡化為單行引號字串。例子:
import ast
script = "text='''Line1\nLine2'''"
code = ast.parse (script, mode='exec')
print (ast.unparse (code))
node = code.body[0].value
print (node.lineno, node.end_lineno)
輸出是:
> text = 'Line1\nLine2'
> 1 2
因此,盡管在決議之前是多行字串,但在未決議時文本會減少為單行引號字串。這使得腳本轉換變得困難,因為在決議轉換后的 AST 圖時多行會丟失。
有沒有辦法用 AST 正確地決議/決議帶有多行字串的腳本?
先感謝您。
uj5u.com熱心網友回復:
對ast.unparse's 底層源代碼的檢查表明,visit_Constant方法的撰寫者_write_constant, 將生成字串repr,除非特別避免反斜杠程序:
class _Unparse:
def _write_constant(self, value):
if isinstance(value, (float, complex)):
...
elif self._avoid_backslashes and isinstance(value, str):
self._write_str_avoiding_backslashes(value)
else:
self.write(repr(value))
默認情況下,_avoid_backslashes設定為,但是,如果字串節點是多行的,則可以通過覆寫并專門呼叫False來正確執行多行字串格式化:visit_Constant_write_str_avoiding_backslashes
import ast
class Unparser(ast._Unparser):
def visit_Constant(self, node):
if isinstance(node.value, str) and node.lineno < node.end_lineno:
super()._write_str_avoiding_backslashes(node.value)
return
return super().visit_Constant(node)
def _unparse(ast_node):
u = Unparser()
return u.visit(ast_node)
script = "text='''Line1\nLine2'''"
print(_unparse(ast.parse(script)))
輸出:
text = """Line1
Line2"""
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491866.html
