Ошибка e999 на питоне

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.

SyntaxError

E999 is reported in the case of failure to compile a file into an Abstract Syntax Tree for the plugins that require it.

Example

Running the following statement would report an E999 error.

print("Hello world)

Output

E999 SyntaxError: EOL while scanning string literal

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)

Уведомления

  • Начало
  • » 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

Офлайн

  • Пожаловаться

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

Статьи по теме

Возможно, вам также будет интересно:

  • Ошибка e99 элвес мф
  • Ошибка e99 штрих м
  • Ошибка e99 на котле baxi
  • Ошибка e98 на котле immergas
  • Ошибка e98 baxi main four

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии