Blank line at end of file как исправить python

юрий пилипенко



Ученик

(151),
на голосовании



3 года назад

В Pycharm все нормально без ошибок, а при сдаче теста выдает такую ошибку .Пустую строку оставляю в конце Precompile check failed:
/solution//solution.py:26:1: W391 blank line at end of file

Голосование за лучший ответ

~Lunna~

Профи

(547)


3 года назад

У вас точно лишние строки. Слева у вас есть нумератор строчек, посмотрите, что у вас их больше. чем та строка, на которой у вас стоит курсор

ЕПрофи (515)

2 года назад

Вот спасибо! У меня оказался целый набор пустых строк)

W391 says that there should be one (and only one) blank line at the end of file. However, flake8 reports the error when there is at least one newline at the end of the file:

$ cat /tmp/test.py
def hello():
    print('hello')


hello()


$ hexdump -C /tmp/test.py
00000000  64 65 66 20 68 65 6c 6c  6f 28 29 3a 0a 20 20 20  |def hello():.   |
00000010  20 70 72 69 6e 74 28 27  68 65 6c 6c 6f 27 29 0a  | print('hello').|
00000020  0a 0a 68 65 6c 6c 6f 28  29 0a 0a                 |..hello()..|
0000002b

You can see above there is in fact one and only one blank line at the end of the file (0a is n). However, when I run flake8, I get the W391 error:

$ flake8 /tmp/test.py
/tmp/test.py:6:1: W391 blank line at end of file

Why is that?

asked Nov 10, 2019 at 2:59

Ben Davis's user avatar

12

Apparently vim automatically adds a newline to every file, which fools me into thinking that last blank line isn’t there. Over time this implicit newline confused me into thinking two newline characters at the end created one blank line.

So, the warning is correct. There should be one and only one n at the end of the file.

answered Nov 10, 2019 at 19:12

Ben Davis's user avatar

Ben DavisBen Davis

12.9k10 gold badges49 silver badges61 bronze badges

W391 говорит, что в конце файла должна быть одна (и только одна) пустая строка. Однако flake8 сообщает об ошибке, если в конце файла есть хотя бы одна новая строка:

$ cat /tmp/test.py
def hello():
    print('hello')


hello()


$ hexdump -C /tmp/test.py
00000000  64 65 66 20 68 65 6c 6c  6f 28 29 3a 0a 20 20 20  |def hello():.   |
00000010  20 70 72 69 6e 74 28 27  68 65 6c 6c 6f 27 29 0a  | print('hello').|
00000020  0a 0a 68 65 6c 6c 6f 28  29 0a 0a                 |..hello()..|
0000002b

Вы можете видеть выше, что на самом деле есть одна и только одна пустая строка в конце файла (0an). Однако, когда я запускаю flake8, я получаю ошибку W391:

$ flake8 /tmp/test.py
/tmp/test.py:6:1: W391 blank line at end of file

Почему это?

1 ответ

Лучший ответ

Очевидно, vim автоматически добавляет новую строку в каждый файл, что заставляет меня думать, что последней пустой строки не существует. Со временем этот скрытый символ новой строки запутал меня, заставив думать, что два символа новой строки в конце создали одну пустую строку.

Итак, предупреждение верно. В конце файла должен быть один и только один n.


3

Ben Davis
10 Ноя 2019 в 19:12

@sigmavirus24

A newline at the end of a file does not mean that there needs to be an empty line. Your editor may not show this to you but the raw bytes would look like:

# your python code
def foo():n
    return barn

If you don’t have the last n there then you will see W391. You seem to be doing

Edited to fix the last example.

@IanLee1521

@davidaames —

Could you provide some sample code where this is an issue? Thanks.

@jkterry1

Hey, I seem to be having this issue as well, with this sample code:

        raise Exception('Error: Incorrect new dag flows on line '
                        + str(i))

@FichteFoll

Since this error is highly whitespace-sensitive, I don’t think it can be reproduced with simple code blocks as those are stripped. Please upload files.

That said, I suspect that the initial problem was that the end of the file looked as follows:

# your python code
def foo():n
    return barn
    n

Note that the last line here is not empty but has 4 spaces. This should raise W391. It was then attempted to fix the error by removing the last newline, but that left the four spaces in the now last line, which caused W292 to be raised.

@hoylemd

As a workaround in the meantime, I have a bit in my editor(vim) config(.vimrc) that strips trailing whitespace whenever a buffer is saved. That might help you (@justinkterry) in the short term, if you use vim and are ok with your editor cleaning whitespace up for you:

function! TrimTrailingWhitespace()
  :%s/s+$//e
endfunction
autocmd BufWritePre *.py :call TrimTrailingWhitespace()

or more concisely:

autocmd BufWritePre *.py :%s/s+$//e  " Trim trailing whitespace

@bsmoliak

W391 appears to supercede W292.

$ echo -n "a = 1" > file.py | pycodestyle file.py
file.py:1:1: W391 blank line at end of file

Seems like W292 should be raised first.

@codypiersall

Hmmm, for what it’s worth, it seems like Vim inserts the newline at the end of the file, but it doesn’t look like there is a newline. I wonder if this is what was happening with the OP?

It took me quite a while to believe that I actually deserved to get W391, but when I hexdump -C /the/file | tail, it was true! The last two bytes were 0a 0a.

@kierun

This is the file I use:

# -*- coding: utf-8 -*-
"""Function to sanitise paths."""

from pathvalidate import sanitize_filename
import os


def sanitise(*paths):
    return os.path.join(*[sanitize_filename(x) for x in paths])

The last line does have a [W292] warning on it. Flake8 passes fine.

Running hexdump, get:

hexdump -C sanitise.py | tail
00000040  70 61 74 68 76 61 6c 69  64 61 74 65 20 69 6d 70  |pathvalidate imp|
00000050  6f 72 74 20 73 61 6e 69  74 69 7a 65 5f 66 69 6c  |ort sanitize_fil|
00000060  65 6e 61 6d 65 0a 69 6d  70 6f 72 74 20 6f 73 0a  |ename.import os.|
00000070  0a 0a 64 65 66 20 73 61  6e 69 74 69 73 65 28 2a  |..def sanitise(*|
00000080  70 61 74 68 73 29 3a 0a  20 20 20 20 72 65 74 75  |paths):.    retu|
00000090  72 6e 20 6f 73 2e 70 61  74 68 2e 6a 6f 69 6e 28  |rn os.path.join(|
000000a0  2a 5b 73 61 6e 69 74 69  7a 65 5f 66 69 6c 65 6e  |*[sanitize_filen|
000000b0  61 6d 65 28 78 29 20 66  6f 72 20 78 20 69 6e 20  |ame(x) for x in |
000000c0  70 61 74 68 73 5d 29 0a                           |paths]).|
000000c8

This is what I see on screen:

screenshot

OS: Centos (7.6.1810), neovim (0.3.2), and neovim-qt (master)…

@FichteFoll

What happens when you run pycodestyle sanitise.py from the command line? This could be a problem in the vim intergation.

@kierun

What happens when you run pycodestyle sanitise.py from the command line? This could be a problem in the vim intergation.

HA! the one thing I did not try. It returns 0, no output whatsoever.

@asottile

I can’t reproduce this (nor @bsmoliak’s example) on the latest version:

$ pycodestyle --version
2.5.0
$ echo -n "a = 1" > file.py | pycodestyle file.py
file.py:1:6: W292 no newline at end of file

Python’s PEP8 code specification, so record the common PEP8 code specification problems and solutions, learn it, and continue to update when you encounter it, develop good habits, and write standardized code!

PEP 8: no newline at end of file

Solution: You need to start a new line at the end of the code and move the cursor to the last carriage return

  • PEP 8: indentation is not a multiple of four
    Solution: Indent is not a multiple of 4, check indent

  • PEP 8: over-indented
    Solution: Excessive indentation, check indentation

  • PEP 8: missing whitespace after’,’
    Solution: There are fewer spaces after the comma, just add spaces, similar to the semicolon or colon after the missing spaces

  • PEP 8: multiple imports on one line
    Solution: Do not refer to multiple libraries in one sentence, for example:import socket, urllib.errorIt is best written as:import socket import urllib.error

  • PEP 8: blank line at end of line
    Solution: There are more spaces at the end of the code, just delete the spaces

  • PEP 8: at least two spaces before inline comment
    Solution: There must be at least two spaces between the code and the comment

  • PEP 8: block comment should start with ‘#’
    Solution: The comment should start with # plus a space

  • PEP 8: inline comment should start with ‘#’
    Solution: The comment should start with # plus a space

  • PEP 8: module level import not at top of file
    Solution: import is not at the top of the file, there may be other code before

  • PEP 8: expected 2 blank lines,found 0
    Solution: Two blank lines are needed, add two blank lines

  • PEP 8: function name should be lowercase
    Solution: Change the function name to lower case

  • PEP 8: missing whitespace around operator
    Solution: Operators (’=’, ‘>’, ‘<’, etc.) lack spaces before and after, just add

  • PEP 8: unexpected spaces around keyword / parameter equals
    Solution: Unexpected spaces appear around the keyword / parameter equal sign, just remove the spaces

  • PEP 8: multiple statements on one line (colon)
    Solution: The multi-line statement is written to one line, for example:if x == 2: print('OK')Write in two lines

  • PEP 8: line too long (82 > 79 characters)
    Solution: The maximum length limit of each line is exceeded 79

  • PEP 8: Simplify chained comparison
    can simplify chain comparisons (for example:if a >= 0 and a <= 9: Can be abbreviated as:if 0 <= a <= 9:


  • If you want to selectively ignore the warning message of the PEP8 code style, you can use the following methods: (Cultivate good habits and write standardized code! It is not recommended to ignore!)

    ①Move the mouse to the place where the warning message appears, pressalt+Enter, Choose to ignore (Ignore) this error:

    ②Select one by oneFile – Settings – Editor – Inspections, Found under PythonPEP8 coding style violation Options, in the lower right cornerIgnore errors Click the plus sign to add the warning message ID that needs to be ignored (see the appendix for ID information), for example, you want to ignoreindentation contains mixed spaces and tabsFor this warning, just add its ID:E101 Just

    Appendix: All warning messages and corresponding IDs, official address: https://pep8.readthedocs.io/en/latest/intro.html#error-codes

    code sample message
    E1 Indentation
    E101 indentation contains mixed spaces and tabs
    E111 indentation is not a multiple of four
    E112 expected an indented block
    E113 unexpected indentation
    E114 indentation is not a multiple of four (comment)
    E115 expected an indented block (comment)
    E116 unexpected indentation (comment)
    E117 over-indented
    E121 (*^) continuation line under-indented for hanging indent
    E122 (^) continuation line missing indentation or outdented
    E123 (*) closing bracket does not match indentation of opening bracket’s line
    E124 (^) closing bracket does not match visual indentation
    E125 (^) continuation line with same indent as next logical line
    E126 (*^) continuation line over-indented for hanging indent
    E127 (^) continuation line over-indented for visual indent
    E128 (^) continuation line under-indented for visual indent
    E129 (^) visually indented line with same indent as next logical line
    E131 (^) continuation line unaligned for hanging indent
    E133 (*) closing bracket is missing indentation
    E2 Whitespace
    E201 whitespace after ‘(‘
    E202 whitespace before ‘)’
    E203 whitespace before ‘:’
    E211 whitespace before ‘(‘
    E221 multiple spaces before operator
    E222 multiple spaces after operator
    E223 tab before operator
    E224 tab after operator
    E225 missing whitespace around operator
    E226 (*) missing whitespace around arithmetic operator
    E227 missing whitespace around bitwise or shift operator
    E228 missing whitespace around modulo operator
    E231 missing whitespace after ‘,’, ‘;’, or ‘:’
    E241 (*) multiple spaces after ‘,’
    E242 (*) tab after ‘,’
    E251 unexpected spaces around keyword / parameter equals
    E261 at least two spaces before inline comment
    E262 inline comment should start with ‘# ‘
    E265 block comment should start with ‘# ‘
    E266 too many leading ‘#’ for block comment
    E271 multiple spaces after keyword
    E272 multiple spaces before keyword
    E273 tab after keyword
    E274 tab before keyword
    E275 missing whitespace after keyword
    E3 Blank line
    E301 expected 1 blank line, found 0
    E302 expected 2 blank lines, found 0
    E303 too many blank lines (3)
    E304 blank lines found after function decorator
    E305 expected 2 blank lines after end of function or class
    E306 expected 1 blank line before a nested definition
    E4 Import
    E401 multiple imports on one line
    E402 module level import not at top of file
    E5 Line length
    E501 (^) line too long (82 > 79 characters)
    E502 the backslash is redundant between brackets
    E7 Statement
    E701 multiple statements on one line (colon)
    E702 multiple statements on one line (semicolon)
    E703 statement ends with a semicolon
    E704 (*) multiple statements on one line (def)
    E711 (^) comparison to None should be ‘if cond is None:’
    E712 (^) comparison to True should be ‘if cond is True:’ or ‘if cond:’
    E713 test for membership should be ‘not in’
    E714 test for object identity should be ‘is not’
    E721 (^) do not compare types, use ‘isinstance()’
    E722 do not use bare except, specify exception instead
    E731 do not assign a lambda expression, use a def
    E741 do not use variables named ‘l’, ‘O’, or ‘I’
    E742 do not define classes named ‘l’, ‘O’, or ‘I’
    E743 do not define functions named ‘l’, ‘O’, or ‘I’
    E9 Runtime
    E901 SyntaxError or IndentationError
    E902 IOError
    W1 Indentation warning
    W191 indentation contains tabs
    W2 Whitespace warning
    W291 trailing whitespace
    W292 no newline at end of file
    W293 blank line contains whitespace
    W3 Blank line warning
    W391 blank line at end of file
    W5 Line break warning
    W503 (*) line break before binary operator
    W504 (*) line break after binary operator
    W505 (*^) doc line too long (82 > 79 characters)
    W6 Deprecation warning
    W601 .has_key() is deprecated, use ‘in’
    W602 deprecated form of raising exception
    W603 ‘<>’ is deprecated, use ‘!=’
    W604 backticks are deprecated, use ‘repr()’
    W605 invalid escape sequence ‘x’
    W606 ‘async’ and ‘await’ are reserved keywords starting with Python 3.7

    Добавить комментарий