Python 使用 ast 解析其中包含换行符的代码

Python parsing code with new line character in them using ast

我有代码的字符串表示,如下面给出的示例

code='''
print('\n')
print('hello world')
'''
import ast
ast.parse(code)

引发错误

print(" 
       ^
 SyntaxError: EOL while scanning string literal

换行符似乎在 parse.Escaping '\n' 解决问题之前将单引号推到下一行,但这需要遍历字符串中的每一行。有更好的方法吗?

似乎正在发生的事情是你的 'code' 在被 ast 解析之前被 python 解释。您可以通过在字符串前放置 'r' 将其作为原始字符串传递,它似乎有效;

code=r'''
print('\n')
print('hello world')
'''

import ast
ast.parse(code)