Python 中带有换行符的 Sublime 文本注释?

Sublime text comments with line break in Python?

我注意到,如果我在 Sublime Text 3 中将一长行 Python 与注释分开,它会将前两个标记为红色(因此是错误的),尽管脚本工作正常。

# This is a long line broken up with comments 
"So I'm ready to attack, gonna lead the pack," + \ # red comment here
"Gonna get a touchdown, gonna take you out," + \ # and here
"That's right, put your pom-poms down, getting everybody fired up" # ok here

我是否必须修改 Python 的 Sublime 配置文件,以我当前的语法风格,使用正则表达式来解决这个问题?

Python 2.7 Language reference has this to say on explicit line joining:

A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

确实对于 Python 2 和 Python 3,您发布的代码被认为无效并产生错误:

  File "/home/tmartin/test.py", line 2
    x = "So I'm ready to attack, gonna lead the pack," +  # red comment here
                                                                           ^
SyntaxError: invalid syntax

Python Online Shell 中执行此操作会提供更具体的错误消息:

Python 3.6.0 (default, Jan 13 2017, 00:00:00) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> "So I'm ready to attack, gonna lead the pack," + \ # red comment here
  File "<stdin>", line 1
    "So I'm ready to attack, gonna lead the pack," + \ # red comment here
                                                                        ^
SyntaxError: unexpected character after line continuation character

因此,Sublime 告诉您代码在这种情况下无效似乎是正确的,如果不修改 Python口译员,虽然我绝不是Python专家。

也就是说,假设这确实对你有用,阻止 Sublime 向你显示这些行的唯一方法是你手动编辑 Sublime 附带的 Python 语法以让它不要将这种情况视为无效。