As @jonrsharpe says, and I agree, this is because the code is being run in Python 2, but linted in Python 3.
From the flake8 documentation on error codes:
We report E999 when we fail to compile a file into an Abstract Syntax Tree for the plugins that require it.
So to prove this is correct, using a file called bad_syntax.py and using the same print syntax as above:
print "test answer", len([])
When I run this with Python 2, everything is happy:
james@codebox:/tmp/lint$ python --version
Python 2.7.12
james@codebox:/tmp/lint$ python bad_syntax.py
test answer 0
Linting with flake8 invoked with a Python 2 environment also passes.
But when I lint with Python 3 (this is running in a virtualenv venv with Python 3 installed), the E999 is returned:
(venv) james@codebox:/tmp/lint$ flake8 --version
3.5.0 (mccabe: 0.6.1, pycodestyle: 2.3.1, pyflakes: 1.6.0) CPython 3.5.2 on Linux
(venv) james@codebox:/tmp/lint$ flake8 bad_syntax.py
bad_syntax.py:1:19: E999 SyntaxError: invalid syntax
I do not think that this is a setting that needs changing inside linter-flake8 because Flake8 will use the version of Python that it is run through. My guess would be that Flake8 is being run on Python 3 because it has been installed inside a Python 3 environment, even though the code is being run on Python 2.
So we’re using Flake8 to lint our Python and it’s being run inside of a CI that I believe doesn’t have the version of Python our application is using † and so it errors like so:
2016-10-28 04:19:46.219 running flake8 for lib/python...
2016-10-28 04:19:47.891 /var/lib/jenkins/workspace/mono/lib/python/cap/services/utils.py:50:14: E999 SyntaxError: invalid syntax
Hence we added # flake8: noqa: E999 to resolve the issue as we know it’s not a syntax error
† to explain: we have a mono repo, where each directory is a different service, and our application has moved some of its modules into a ‘shared’ directory so other apps can use that code. The problem there is that we have two CI’s; one CI uses Docker to run our app and its tests/linter etc with the relevant and correct environment √ the other CI doesn’t use Docker and uses Python 2 instead of Python 3 which our app uses and it runs its own integration tests against all the ‘services’ (i.e. directories within our mono repo)
flake8 testing of https://github.com/3b1b/manim on Python 3.6.3
$ flake8 . —count —select=E901,E999,F821,F822,F823 —show-source —statistics
./active_projects/alt_calc.py:2212:44: E999 SyntaxError: invalid syntax
for x_min, x_max in (-10, -0.1), (0.1, 10)
^
./active_projects/eola2/determinant_puzzle.py:104:35: E999 SyntaxError: invalid syntax
for i, j in (0, 0), (1, 1), (0, 1), (1, 0)
^
./active_projects/eop/bayes.py:1018:38: E999 SyntaxError: invalid syntax
for s, num in ("", p_str), ("\text{not }", q_str)
^
./active_projects/eop/bayes_footnote.py:489:35: E999 SyntaxError: invalid syntax
for s1, s2 in ("", ""), ("= 0.001", "= 0.999")
^
./active_projects/eop/chapter1/prob_dist_visuals.py:293:22: E999 SyntaxError: invalid syntax
TexMobject("{1over 8}").scale(0.5).next_to(brace, DOWN)
^
./old_projects/WindingNumber_G.py:1543:47: E999 SyntaxError: invalid syntax
for x, fx, color in (x0, fx0, RED), (x1, fx1, GREEN)
^
./old_projects/bell.py:222:38: E999 SyntaxError: invalid syntax
for here, x in (here1, 0), (here2, 4)
^
./old_projects/crypto.py:2319:34: E999 SyntaxError: invalid syntax
for u1, u2 in (-1, 1), (1, 1), (-1, -1)
^
./old_projects/efvgt.py:2798:52: E999 SyntaxError: invalid syntax
for mob, axis in (square, raw_axis), (cube, posed_axis)
^
./old_projects/fourier.py:3788:38: E999 SyntaxError: invalid syntax
for p1, p2 in ("e", "t}"), ("g({}", "t}"), ("\int", "dt")
^
./old_projects/hanoi.py:2033:39: E999 SyntaxError: invalid syntax
for d, color in (3, GREEN), (2, RED), (1, BLUE_C)
^
./old_projects/highD.py:1987:52: E999 SyntaxError: invalid syntax
for mob in slider.real_estate_ticks, slider.dial
^
./old_projects/leibniz.py:3449:31: E999 SyntaxError: invalid syntax
for i, d in (1, 4), (3, 4), (2, 2)
^
./old_projects/triples.py:1747:31: E999 SyntaxError: invalid syntax
for u, v in (2, 1), (3, 2), (4, 1)
^
./old_projects/wallis.py:3489:27: E999 SyntaxError: invalid syntax
for part in pi, pi.dot, pi.title
^
./old_projects/waves.py:1780:41: E999 SyntaxError: invalid syntax
for ov, A in (h_ov, h_A), (v_ov, v_A)
^
./old_projects/wcat.py:529:31: E999 SyntaxError: invalid syntax
for i, j in (0, 2), (1, 3)
^
./old_projects/eoc/chapter1.py:2332:47: E999 SyntaxError: invalid syntax
for mob, tex in (x_squared, f_tex), (dx, "dx"), (dA, "dA")
^
./old_projects/eoc/chapter10.py:1792:42: E999 SyntaxError: invalid syntax
for c, arc in (c2, 0.9*np.pi), (c0, np.pi)
^
./old_projects/eoc/chapter3.py:2088:28: E999 SyntaxError: invalid syntax
for s in square, bigger_square
^
./old_projects/eoc/chapter6.py:399:35: E999 SyntaxError: invalid syntax
for i, j in (1, 0), (0, 1)
^
./old_projects/eoc/chapter8.py:1922:31: E999 SyntaxError: invalid syntax
for i, j in (0, 1), (1, 0), (1, 2)
^
./old_projects/eoc/footnote.py:637:49: E999 SyntaxError: invalid syntax
for mob, tex in (self.ddf, "df"), (self.dx_squared, "dx")
^
./old_projects/eola/chapter10.py:312:24: E999 SyntaxError: invalid syntax
for u in -1, 1
^
./old_projects/eola/chapter11.py:508:28: E999 SyntaxError: invalid syntax
for u in -1, 1
^
./old_projects/eola/chapter2.py:242:43: E999 SyntaxError: invalid syntax
for v, label in (v1, v1_label), (v2, v2_label)
^
./old_projects/eola/chapter6.py:382:35: E999 SyntaxError: invalid syntax
for i, j in (1, 3), (2, 6)
^
./old_projects/eola/chapter8.py:1162:33: E999 SyntaxError: invalid syntax
for v1, v2 in (v, w), (v.target, w.target)
^
./utils/iterables.py:113:16: E999 SyntaxError: invalid syntax
lambda (f1, args1), (f2, args2): (lambda x: f1(f2(x, *args2), *args1)),
^
./utils/simple_functions.py:15:28: F821 undefined name 'xrange'
denom = reduce(op.mul, xrange(1, r + 1), 1)
^
./utils/simple_functions.py:16:28: F821 undefined name 'xrange'
numer = reduce(op.mul, xrange(n, n - r, -1), 1)
^
29 E999 SyntaxError: invalid syntax
2 F821 undefined name 'xrange'
31
Уведомления
- Начало
- » Python для новичков
- » Ошибка E999
#1 Авг. 16, 2018 17:03:38
Ошибка E999
Добрый день! При написании программы столкнулся с ошибкой E999, все перепробывал, не могу исправить.
По отдельности
try: Number = int('{}'.format(alice_request) client = Client('') result = client.service.Web(Number) except Exception: print('Произошла ошибка') else: if not result or result =="-3": print('Произошла ошибка') else: print(result['return'])
Работает нормально
https://pp.userapi.com/c846217/v846217140/c666d/AsQKXX9Zqog.jpg
В чем может быть проблема?
Python 3.7
Отредактировано megabait1024@mail.ru (Авг. 16, 2018 17:04:13)
Офлайн
- Пожаловаться
#2 Авг. 17, 2018 00:11:40
Ошибка E999
34 строка не хватает закрывающей скобки.
И как это может работать нормально при ошибке синтаксиса?
_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com
Офлайн
- Пожаловаться
Flake8 and its plugins assign a code to each message that we refer to as an
error code (or violation). Most plugins will list their error
codes in their documentation or README.
Flake8 installs pycodestyle, pyflakes, and mccabe by default and
generates its own error codes for pyflakes:
|
Code |
Example Message |
|---|---|
|
F401 |
|
|
F402 |
import |
|
F403 |
‘from |
|
F404 |
future import(s) |
|
F405 |
|
|
F406 |
‘from |
|
F407 |
an undefined |
|
F501 |
invalid |
|
F502 |
|
|
F503 |
|
|
F504 |
|
|
F505 |
|
|
F506 |
|
|
F507 |
|
|
F508 |
|
|
F509 |
|
|
F521 |
|
|
F522 |
|
|
F523 |
|
|
F524 |
|
|
F525 |
|
|
F541 |
f-string without any placeholders |
|
F601 |
dictionary key |
|
F602 |
dictionary key variable |
|
F621 |
too many expressions in an assignment with star-unpacking |
|
F622 |
two or more starred expressions in an assignment |
|
F631 |
assertion test is a tuple, which is always |
|
F632 |
use |
|
F633 |
use of |
|
F634 |
if test is a tuple, which is always |
|
F701 |
a |
|
F702 |
a |
|
F703 |
a |
|
F704 |
a |
|
F706 |
a |
|
F707 |
an |
|
F721 |
syntax error in doctest |
|
F722 |
syntax error in forward annotation |
|
F723 |
syntax error in type comment |
|
F811 |
redefinition of unused |
|
F821 |
undefined name |
|
F822 |
undefined name |
|
F823 |
local variable |
|
F831 |
duplicate argument |
|
F841 |
local variable |
|
F901 |
|
We also report one extra error: E999. We report E999 when we fail to
compile a file into an Abstract Syntax Tree for the plugins that require it.
mccabe only ever reports one violation — C901 based on the
complexity value provided by the user.
Users should also reference pycodestyle’s list of error codes.
As @jonrsharpe says, and I agree, this is because the code is being run in Python 2, but linted in Python 3.
From the flake8 documentation on error codes:
We report E999 when we fail to compile a file into an Abstract Syntax Tree for the plugins that require it.
So to prove this is correct, using a file called bad_syntax.py and using the same print syntax as above:
print "test answer", len([])
When I run this with Python 2, everything is happy:
james@codebox:/tmp/lint$ python --version
Python 2.7.12
james@codebox:/tmp/lint$ python bad_syntax.py
test answer 0
Linting with flake8 invoked with a Python 2 environment also passes.
But when I lint with Python 3 (this is running in a virtualenv venv with Python 3 installed), the E999 is returned:
(venv) james@codebox:/tmp/lint$ flake8 --version
3.5.0 (mccabe: 0.6.1, pycodestyle: 2.3.1, pyflakes: 1.6.0) CPython 3.5.2 on Linux
(venv) james@codebox:/tmp/lint$ flake8 bad_syntax.py
bad_syntax.py:1:19: E999 SyntaxError: invalid syntax
I do not think that this is a setting that needs changing inside linter-flake8 because Flake8 will use the version of Python that it is run through. My guess would be that Flake8 is being run on Python 3 because it has been installed inside a Python 3 environment, even though the code is being run on Python 2.
Уведомления
- Начало
- » Python для новичков
- » Ошибка E999
#1 Авг. 16, 2018 17:03:38
Ошибка E999
Добрый день! При написании программы столкнулся с ошибкой E999, все перепробывал, не могу исправить.
По отдельности
try: Number = int('{}'.format(alice_request) client = Client('') result = client.service.Web(Number) except Exception: print('Произошла ошибка') else: if not result or result =="-3": print('Произошла ошибка') else: print(result['return'])
Работает нормально
https://pp.userapi.com/c846217/v846217140/c666d/AsQKXX9Zqog.jpg
В чем может быть проблема?
Python 3.7
Отредактировано megabait1024@mail.ru (Авг. 16, 2018 17:04:13)
Офлайн
- Пожаловаться
#2 Авг. 17, 2018 00:11:40
Ошибка E999
34 строка не хватает закрывающей скобки.
И как это может работать нормально при ошибке синтаксиса?
_________________________________________________________________________________
полезный блог о python john16blog.blogspot.com
Офлайн
- Пожаловаться
flake8 — синтаксическая ошибка E999 с аргументом метакласса python3
Рохит
Я использую vim для разработки на Python с flake8 в качестве линтера. Ниже приведен пример кода, содержащего метакласы. Flake8 показывает ошибку E999 SyntaxError: недопустимый синтаксис (E) в строке class Spam(metaclass=MyMeta). Я использую python3, и это правильный синтаксис для указания пользовательских метаклассов в python3.
class MyMeta(type):
def __new__(cls, clsname, bases, clsbody):
upper_case = {}
for k, v in clsbody.items():
if not k.startswith('__'):
upper_case[k.upper()] = v
return super().__new__(cls, clsname, bases, upper_case)
class Spam(metaclass=MyMeta):
foo = 'bar'
Есть способ исправить это?
jsbueno
Что ж, вы редактируете код Python3, и ваш flake8, очевидно, проверяет синтаксис Python2.
Глядя в Интернет, можно увидеть, что простой способ заставить flake8 проверять Python3 — это запустить его из Python3.
Скорее всего, вы работаете в Linux или другом Unix (я понял подсказку из использования VIM), поэтому, если flake8 установлен в масштабе всей системы, удалите его и установите в Python3 (в Fedora и Redhatish дистрибутивах это так dnf uninstall python2-flake8 dnf install python3-flake8).
Более правильный подход может заключаться в том, чтобы просто настроить virtualenv для вашего проекта Python с желаемой версией Python, установить flake8 внутри этого virtualenv pip install flake8, а также запустить VIM изнутри вашего virtualenv, чтобы все сценарии или программы Python, которые он запускал, были на та же среда, и даже такие вещи, как расширенное автозаполнение, могут проверять библиотеки, которые фактически использует ваш проект.
Эта статья взята из Интернета, укажите источник при перепечатке.
Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.
Отредактировано в2020-11-26
Статьи по теме
