Python 脚本是否应该以换行结束? Pylint自相矛盾?

Python script should end with new line or not ? Pylint contradicting itself?

我是 Pylint 的新手,当我 运行 它针对我的脚本时,我得到这个输出:

C: 50, 0: Trailing newlines (trailing-newlines)

在这里,Pylint 说最后换行是不好的。

我喜欢在我的脚本末尾有一个新行,所以我想我会禁用这个警告。 我做了一些 google 网络搜索并找到了这个: http://pylint-messages.wikidot.com/messages:c0304

C0304 Message

Final newline missing

Description

Used when a Python source file has no line end character(s) on its last line.

This message belongs to the format checker. Explanation

While Python interpreters typically do not require line end character(s) on the last line, other programs processing Python source files may do, and it is simply good practice to have it. This is confirmed in Python docs: Line Structure which states that a physical line is ended by the respective line end character(s) of the platform.

在这里,Pylint 说错过最后的换行符是不好的。

(A) 正确的看法是什么? (B) 如何禁用最后一行的检查?

{{ 编辑:事实证明这不是 Pylint 的问题;这是 vim 的问题,它会自动添加 eol :VIM Disable Automatic Newline At End Of File }}

您收到的 pylint 警告是抱怨您有多个尾随换行符。当根本没有尾随换行符时,会出现 C0304 消息。

这些消息并不矛盾,它们表示不同的问题。

你需要至少一个换行符的原因是,如果文件结束并且最后一行有文本但文件末尾没有换行符,历史上有些工具会出现问题。写得不好的工具可能会错过最后一行的处理,甚至更糟的是可以读取最后一行之后的随机内存(尽管用 Python 编写的工具不太可能发生这种情况,但用 C 编写的工具可能会发生)。

所以你必须确保有一个换行符终止最后一个非空行。

但是您也不希望文件末尾有任何完全空白的行。它们实际上不会产生错误,但它们不整洁。所以删除任何空行,你应该没问题。

C0304 Final newline missing is the error occures when a Python source file has no line end character(s) on its last line.

我告诉你禁用pylint warring的方法

要禁用警告,您可以简单地在 .py 文件中添加以下行,通常在导入之前添加是个好习惯。

# disabling:
# C0304: Trailing newlines (trailing-newlines)
# pylint: disable=C0304

或 您可以创建一个配置文件~/.pylintrc 这允许您忽略您不关心的警告。