SyntaxError: EOL while scanning string literal with ast.parse

SyntaxError: EOL while scanning string literal with ast.parse

以下有效python代码

In [49]: print('hello\n')
hello

但是当我使用 ast 模块的解析方法时 returns,语法错误

In [47]: code = "print('hello\n')"

In [48]: ast.parse(code)
  File "<unknown>", line 1
    print('hello
           ^
SyntaxError: EOL while scanning string literal

In [51]: eval(code)
  File "<string>", line 1
    print('hello
        ^
SyntaxError: invalid syntax

为什么在这种情况下 ast 模块无法解析有效的 python 代码?

你应该写:

code = "print('hello\n')"

你必须在代码

中转义\
code = "print('hello\n')"
ast.parse(code)
# <_ast.Module object at 0x7fd68cb48cc0> 

或者您可以添加 r 前缀以指示字符串中的所有内容都需要转义

code = r"print('hello\n')"
ast.parse(code)
# <_ast.Module object at 0x7fd68cb48ef0>

您需要使用多行注释 '''YourCode'''"""YourCode"""

例如:

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