Ошибка unable to import

If you want to walk up from the current module/file that was handed to pylint looking for the root of the module, this will do it.

[MASTER]
init-hook=sys.path += [os.path.abspath(os.path.join(os.path.sep, *sys.argv[-1].split(os.sep)[:i])) for i, _ in enumerate(sys.argv[-1].split(os.sep)) if os.path.isdir(os.path.abspath(os.path.join(os.path.sep, *sys.argv[-1].split(os.sep)[:i], '.git')))][::-1]

If you have a python module ~/code/mymodule/, with a top-level directory layout like this

~/code/mymodule/
├── .pylintrc
├── mymodule/
│   └── src.py
└── tests/
    └── test_src.py

Then this will add ~/code/mymodule/ to your python path and allow for pylint to run in your IDE, even if you’re importing mymodule.src in tests/test_src.py.

You could swap out a check for a .pylintrc instead but a git directory is usually what you want when it comes to the root of a python module.

Before you ask

The answers using import sys, os; sys.path.append(...) are missing something that justifies the format of my answer. I don’t normally write code that way, but in this case you’re stuck dealing with the limitations of the pylintrc config parser and evaluator. It literally runs exec in the context of the init_hook callback so any attempt to import pathlib, use multi-line statements, store something into variables, etc., won’t work.

A less disgusting form of my code might look like this:

import os
import sys

def look_for_git_dirs(filename):
    has_git_dir = []
    filename_parts = filename.split(os.sep)
    for i, _ in enumerate(filename_parts):
        filename_part = os.path.abspath(os.path.join(os.path.sep, *filename_parts[:i]))
        if os.path.isdir(os.path.join(filename_part, '.git')):
            has_git_dir.append(filename_part)
    return has_git_dir[::-1]

# don't use .append() in case there's < 1 or > 1 matches found
sys.path += look_for_git_dirs(sys.argv[-1])

I wish I could have used pathlib.Path(filename).parents it would have made things much easier.

Back to top

Edit this page

Toggle table of contents sidebar

Message emitted:

Unable to import %s

Description:

Used when pylint has been unable to import a module.

Problematic code:

from patlib import Path  # [import-error]

Correct code:

from pathlib import Path

Additional details:

This can happen if you’re importing a package that is not installed in your environment, or if you made a typo.

The solution is to install the package via pip/setup.py/wheel or fix the typo.

Created by the imports checker.

Are you looking for an answer to the topic “pylint unable to import“? We answer all your questions at the website Brandiscrafts.com in category: Latest technology and computer news updates. You will find the answer right below.

Keep Reading

Pylint Unable To Import

Pylint Unable To Import

How do I fix pylint import error in VSCode?

Python Unresolved Import: How to Solve Pylint Error

  1. If you have just started coding Python in VS Code, make sure the python environment has been set. …
  2. If you are working with Visual Studio Code and import any library, you will face this error: “unresolved import”. …
  3. Then reload the VSCode, and it will fix that error.

How do I fix the import error in VSCode?

Set the correct Python path in VSCode

In order to fix Unresolved Import in VSCode, you have to set python. pythonPath key in the settings to the correct value. You can quickly open the settings. json editor by accessing File > Preferences or press Ctrl + , key combination.


Fixed Pylint (import-error) Unable to import – How to fix Unable to import ” pylint(import-error)

Fixed Pylint (import-error) Unable to import – How to fix Unable to import ” pylint(import-error)

Fixed Pylint (import-error) Unable to import – How to fix Unable to import ” pylint(import-error)

Images related to the topicFixed Pylint (import-error) Unable to import – How to fix Unable to import ” pylint(import-error)

Fixed Pylint (Import-Error) Unable To Import  - How To Fix Unable To Import '' Pylint(Import-Error)

Fixed Pylint (Import-Error) Unable To Import – How To Fix Unable To Import ” Pylint(Import-Error)

How do you run a pylint?

  1. Summary. This page describes how to run pylint locally on to your machines.
  2. To Install Pylint. Windows, Mac OS X & Debian: pip install pylint. …
  3. To Run Pylint. Change the directory to where the file is located on command prompt. …
  4. To Integrate Pylint. PyCharm – JetBrains. …
  5. To Disable.

What is the use of pylint in Python?

What is Pylint? It is a static code analysis tool to identify errors in Python code and helps programmers enforce good coding style. This tool enables them debugging complex code with less manual work. It is one of the tools which gets used for test-driven development (TDD).

How do you fix a pylint error?

Most of the errors reported by pylint can be fixed with autopep8. Additionally, if you are using Pycharm as your editor, it has the option to reformat-code which will help to solve most of the issues reported by pylint .

How do I fix Visual Studio Code lint issues?

Go to File > Preferences > Settings (or Code > Preferences > Settings). Then click settings. json . Now, undo the fixes you made to the JavaScript file you created earlier.

How do you fix an import error in Python?

Here is a step-by-step solution:

  1. Add a script called run.py in /home/bodacydo/work/project and edit it like this: import programs.my_python_program programs.my_python_program.main() (replace main() with your equivalent method in my_python_program .)
  2. Go to /home/bodacydo/work/project.
  3. Run run.py.

See some more details on the topic pylint unable to import here:


Linting | Python in Visual Studio Code

1. Unable to import (pylint) · Open the terminal window · Activate the relevant python virtual environment · Ensure Pylint is installed within this virtual …

+ Read More

PyLint “Unable to import” error – how to set PYTHONPATH?

I’m running PyLint from inside Wing IDE on Windows. I have a sub-directory (package) in my project and inside the package I import a module from the top …

+ Read More

PyLint “Unable to import” error – how to set PYTHONPATH?

PyLint “Unable to import” error – how to set PYTHONPATH? · 1) sys.path is a list. · 2) The problem is sometimes the sys.path is not your virtualenv.path and you …

+ Read More Here

Pylint unable to import vscode. Make sure you selected the …

Pylint unable to import vscode. Make sure you selected the right python interpreter for your project (in case you are using virtualenv/pipenv/other): When …

+ Read More

How do I import a Python library code into Visual Studio?

Settings and configuration#

  1. Open VS Code.
  2. Within VS Code, open the Command Palette (ctrl+shift+p)
  3. Select Python: Select Interpreter.
  4. Select the interpreter that you installed or that was installed by the Coding Pack.

How do I import a package code into Visual Studio?

Import packages#

Run the command Go: Add Import to get a list of packages that can be imported to your Go file. Choose one and it will get added in the import block of your Go file.

How do I know if pylint is installed?

1 Answer

  1. Check if Pylint is installed successfully: As a Python code analysis toolkit, Pylint is stored in the Python environment as a Pylint module, so we can use ” pip show pylint ” in the Visual Studio Code terminal to check its installation:
  2. The use of Pylin t in Visual Studio Code:

How do I open a pylint file?

Installing Pylint (Maya 2017-2020)

  1. Open a Command Prompt or Terminal. On Windows, navigate to the Python root directory (install location)
  2. Run the following command: python -m pip install pylint.
  3. Note the location of the pylint executable: Windows – pylint.exe should be in the Scripts folder (Python root directory)

How do I run a pylint code in Visual Studio?

Set PyLint command-line options

In Visual Studio Solution Explorer, right-click your project, select Add > Existing Item, navigate to the new . pylintrc file, select it, and select Add.


Pylint (Import Error) Fixed!! || Unable to import ‘requests’ pylint import error || VScode || Part2

Pylint (Import Error) Fixed!! || Unable to import ‘requests’ pylint import error || VScode || Part2

Pylint (Import Error) Fixed!! || Unable to import ‘requests’ pylint import error || VScode || Part2

Images related to the topicPylint (Import Error) Fixed!! || Unable to import ‘requests’ pylint import error || VScode || Part2

Pylint (Import Error) Fixed!! || Unable To Import 'Requests' Pylint Import Error || Vscode || Part2

Pylint (Import Error) Fixed!! || Unable To Import ‘Requests’ Pylint Import Error || Vscode || Part2

Is pylint safe?

Is pylint safe to use? The python package pylint was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use.

How do I update pylint?

Upgrading Pylint

To upgrade to the absolute latest version, run the following command: pip install pylint –upgrade.

What is pylint library?

Pylint is a Python static code analysis tool which looks for programming errors, helps enforcing a coding standard, sniffs for code smells and offers simple refactoring suggestions.

What are pylint errors?

Pylint has a standard format to its output. When there is a syntax error, it will not show a code rating. Depending on your version of Pylint, you may or may not see the first line informing you what . pylintrc configuration file you’re using. This allows you to verify that you’re using the one you intended to.

Which linter is best for Python?

Which Python linter should I use?

  • Flake8 is my personal favorite these days. It’s fast and has a low rate of false positives. …
  • Pylint is another good choice. It takes a little more effort to set up than Flake8 and also triggers more false positives.

How does PyCharm integrate with pylint?

Now that you have installed pylint on your system, you can configure its integration with PyCharm. Press Ctrl+Alt+S to open the IDE settings and select Tools | External Tools. button to add a new external tool.

How do you fix ESLint issues?

There are three ways that ESLint fix can be run:

  1. eslint –fix.
  2. eslint –fix-dry-run.
  3. eslint –fix –fix-type.

How do I enable vs lint in code?

Here’s how to do it:

  1. Install VSCode ESLint Plugin. In VSCode, open the extension browser with the button on the left. On the Mac, the keyboard shortcut Cmd+Shift+X should do the same. …
  2. Configure VSCode Settings to use ESLint for Formatting. Open up VSCode’s settings.

How do I enable ESLint?

Install ESLint

  1. In the embedded Terminal ( Alt+F12 ) , type one of the following commands: npm install –g eslint for global installation. npm install –save-dev eslint to install ESLint as a development dependency.
  2. Optionally, install additional plugins, for example, eslint-plugin-react to lint React applications.

Why cant I import a Python module?

This is caused by the fact that the version of Python you’re running your script with is not configured to search for modules where you’ve installed them. This happens when you use the wrong installation of pip to install packages.


How to FIX VSCode error in PyQt5 import pylint(no-name-in-module) pylint(missing-class-docstring)

How to FIX VSCode error in PyQt5 import pylint(no-name-in-module) pylint(missing-class-docstring)

How to FIX VSCode error in PyQt5 import pylint(no-name-in-module) pylint(missing-class-docstring)

Images related to the topicHow to FIX VSCode error in PyQt5 import pylint(no-name-in-module) pylint(missing-class-docstring)

How To Fix Vscode Error In Pyqt5 Import  Pylint(No-Name-In-Module)  Pylint(Missing-Class-Docstring)

How To Fix Vscode Error In Pyqt5 Import Pylint(No-Name-In-Module) Pylint(Missing-Class-Docstring)

What causes import error in Python?

Conclusion – Python ImportError

In Python, ImportError occurs when the Python program tries to import module which does not exist in the private table. This exception can be avoided using exception handling using try and except blocks.

How do I import a file into Python?

the best way to import . py files is by way of __init__.py . the simplest thing to do, is to create an empty file named __init__.py in the same directory that your.py file is located.

  1. Just import file without the . …
  2. A folder can be marked as a package, by adding an empty __init__.py file.

Related searches to pylint unable to import

  • pylint e0401 unable to import
  • pylint(import-error but works)
  • pylint ignore unable to import
  • unable to import ‘numpy’pylint(import-error)
  • pylint unable to import disable
  • pylint unable to import ignore
  • pylint error unable to import vscode
  • pylint unable to import vscode
  • pre-commit pylint unable to import
  • pylint unable to import virtualenv
  • unable to import (import-error) pylint
  • vscode pylint unable to import
  • pylint unable to import module in same directory
  • pylint unable to import django
  • pre commit pylint unable to import
  • pylint unable to import venv
  • pylint unable to import pycharm
  • pylint unable to import flask
  • pylintimport error but works
  • vscode pylint unable to import local module
  • pylint unable to import pipenv
  • unable to import pytest
  • python pylint unable to import

Information related to the topic pylint unable to import

Here are the search results of the thread pylint unable to import from Bing. You can read more if you want.


You have just come across an article on the topic pylint unable to import. If you found this article useful, please share it. Thank you very much.

If you want to walk up from the current module/file that was handed to pylint looking for the root of the module, this will do it.

[MASTER]
init-hook=sys.path += [os.path.abspath(os.path.join(os.path.sep, *sys.argv[-1].split(os.sep)[:i])) for i, _ in enumerate(sys.argv[-1].split(os.sep)) if os.path.isdir(os.path.abspath(os.path.join(os.path.sep, *sys.argv[-1].split(os.sep)[:i], '.git')))][::-1]

If you have a python module ~/code/mymodule/, with a top-level directory layout like this

~/code/mymodule/
├── .pylintrc
├── mymodule/
│   └── src.py
└── tests/
    └── test_src.py

Then this will add ~/code/mymodule/ to your python path and allow for pylint to run in your IDE, even if you’re importing mymodule.src in tests/test_src.py.

You could swap out a check for a .pylintrc instead but a git directory is usually what you want when it comes to the root of a python module.

Before you ask

The answers using import sys, os; sys.path.append(...) are missing something that justifies the format of my answer. I don’t normally write code that way, but in this case you’re stuck dealing with the limitations of the pylintrc config parser and evaluator. It literally runs exec in the context of the init_hook callback so any attempt to import pathlib, use multi-line statements, store something into variables, etc., won’t work.

A less disgusting form of my code might look like this:

import os
import sys

def look_for_git_dirs(filename):
    has_git_dir = []
    filename_parts = filename.split(os.sep)
    for i, _ in enumerate(filename_parts):
        filename_part = os.path.abspath(os.path.join(os.path.sep, *filename_parts[:i]))
        if os.path.isdir(os.path.join(filename_part, '.git')):
            has_git_dir.append(filename_part)
    return has_git_dir[::-1]

# don't use .append() in case there's < 1 or > 1 matches found
sys.path += look_for_git_dirs(sys.argv[-1])

I wish I could have used pathlib.Path(filename).parents it would have made things much easier.

IgorDV
Модуль импортируется, доступ к содержимому есть.
И все равно подчеркивает import — Unable to import ‘util_date’pylint(import-error)

Ну это сугубо ограничения IDE.
Вы же понимаете, что для того, чтобы правильно импортировать модуль util_date надо выполнить код?
Вот эта ваша строка

 sys.path.append(os.path.join(sys.path, ..util))

должна быть выполнена перед импортом. Это не магия, не специальный синтаксис, это обычный вызов функции в питоне.
А теперь подумайте, а откуда IDE должна знать, что пути к библиотеке меняются по ходу выполнения программы? Откуда она знает, что вы вызываете функцию, которая добавляет путь к каталогу вашего модуля? Вы подразумеваете, что IDE выполняет код, который читает. Это было бы вообще говоря довольно опасное поведение, давайте представим, что мы пишем программу, котоая удаляет все файлы из домашней директории. И вот мы написали программу, а ИДЕ взяла и без спроса её выполнила.
Ну и вообще, кто мешает написать вот такой код

 if DEVELOP:
    sys.path.append(os.path.join(sys.path, 'develop',  'util'))
elif PRODUCTION:
    sys.path.append(os.path.join(sys.path, 'prod',  'util'))
elif TEST:
    .....

И как ваша ИДЕ должна определить, какой именно модуль вы собрались поключать?

1. Unable to import (pylint)

  • Scenario: You have a module installed, however the linter in the IDE is complaining about; not being able to import the module, hence error messages such as the following are displayed as linter errors:
.. unable to import 'xxx' .. 
  • Cause: The Python extension is most likely using the wrong version of Pylint.

Solution 1: (configure workspace settings to point to fully qualified python executable):

  1. Open the workspace settings (settings.json)
  2. Identify the fully qualified path to the python executable (this could even be a virtual environment)
  3. Ensure Pylint is installed for the above python environment
  4. Configure the setting “pythonPath” to point to (previously identified) the fully qualified python executable.
"python.pythonPath": "/users/xxx/bin/python"

Solution 2: (open VS Code from an activated virtual environment):

  1. Open the terminal window
  2. Activate the relevant python virtual environment
  3. Ensure Pylint is installed within this virtual environment pip install pylint
  4. Close all instances of VS Code
  5. Launch VS Code from within this terminal window
    (this will ensure the VS Code process will inherit all of the Virtual Env environment settings)

2. Linting with xxx failed. …

Listing could fail due to a number of reasons. Please check each of the following.

Cause: The path to the python executable is incorrect
Solution: Configure the path to the python executable in the settings.json

Cause: The linter has not been installed in the Python environment being used
Solution: Identify the Python environment (executable) configured in settings.json. Next install the linter(s) against this Python environment (use the corresponding Pip).

Cause: The Path to the linter is incorrect
Solution: If you have provided a custom path to the linter in settings.json, then ensure this file path exist.

For further information on configuring Linters can be found here.

3. Ignore certain messages

It is possible you would like to ignore certain linter messages. This could be done easily.
Generally most linters support configuration files, hence all you need to do is create the relevant configuration file and ignore the appropriate error message.
If on the other hand the linters support the ability to ignore certain messages via command line args, this can be done as well.

Solution: Add relevant command line args to ignore certain messages
Here we’ll assume you use a TAB character as indentation of python code instead of 4 or 2 spaces.
Pylint would generally display a warning for this with the error code W0312.
In order to disable this particular message all one needs to do is as follows in the settings.json file:

 "python.linting.pylintArgs": [
        "--disable=W0312"
 ],

Note: You could apply the above configuration settings in your user settings file, so that it applies to all workspaces.
This saves you from having to define these settings for every single workspace (every time).

For further information on configuring Linters can be found here.

Вопрос:

Я запускаю PyLint из внутренней среды Wing IDE в Windows. У меня есть подкаталог (пакет) в моем проекте, и внутри пакета я импортирую модуль с верхнего уровня, т.е.

__init__.py
myapp.py
one.py
subdir
__init__.py
two.py

Внутри two.py У меня есть import one, и это отлично работает во время выполнения, потому что каталог верхнего уровня (из которого выполняется myapp.py) находится в пути Python. Однако, когда я запускаю PyLint на two.py, это дает мне ошибку:

F0401: Unable to import 'one'

Как это исправить?

Ответ №1

Есть два варианта, которые мне известны.

Во-первых, измените переменную среды PYTHONPATH, чтобы она включала каталог над вашим модулем.

Либо отредактируйте ~/.pylintrc, чтобы он включал каталог над вашим модулем, например:

[MASTER]
init-hook='import sys; sys.path.append("/path/to/root")'

(или в другой версии pylint, ловушка инициализации требует, чтобы вы изменили [General] на [MASTER])

Оба эти варианта должны работать.

Надеюсь, это поможет.

Ответ №2

1) sys.path – это список.

2) Проблема в том, что sys.path – это не ваш virtualenv.path, и вы хотите использовать pylint в вашем virtualenv

3) Так, как и сказано, используйте init-hook (обратите внимание в ‘и “синтаксический анализ pylint строго)

[Master]
init-hook='sys.path = ["/path/myapps/bin/", "/path/to/myapps/lib/python3.3/site-packages/", ... many paths here])'

или

[Master]
init-hook='sys.path = list(); sys.path.append("/path/to/foo")'

.. и

pylint --rcfile /path/to/pylintrc /path/to/module.py

Ответ №3

Решение об изменении пути в init-hook является хорошим, но мне не нравится тот факт, что мне пришлось добавлять абсолютный путь туда, в результате я не могу поделиться этим файлом pylintrc среди разработчиков проекта. Это решение, использующее относительный путь к файлу pylintrc, работает лучше для меня:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

Обратите внимание, что pylint.config.PYLINTRC также существует и имеет то же значение, что и find_pylintrc().

Ответ №4

У вас есть пустой файл __init__.py в обоих каталогах, чтобы позволить python знать, что dirs являются модулями?

Основной контур, когда вы не работаете из папки (т.е., может быть, из pylint, хотя я этого не использовал):

topdir
__init__.py
functions_etc.py
subdir
__init__.py
other_functions.py

Так интерпретатор python знает модуль без ссылки на текущий каталог, поэтому, если pylint работает от своего абсолютного пути, он сможет получить доступ к functions_etc.py как topdir.functions_etc или topdir.subdir.other_functions, при условии, что topdir находится на PYTHONPATH.

UPDATE: если проблема не в файле __init__.py, возможно, просто попробуйте скопировать или переместить ваш модуль на c:Python26Libsite-packages – это обычное место для размещения дополнительных пакетов и, безусловно, будет на вашем пути python. Если вы знаете, как делать символические ссылки Windows или эквивалентные (я этого не делаю!), Вы можете сделать это вместо этого. Есть еще много опций здесь: http://docs.python.org/install/index.html, включая возможность добавления sys.path с каталогом уровня вашего кода разработки, но на практике я обычно просто символически связываю свой локальный каталог разработки с сайтами-пакетами – копирование его имеет тот же эффект.

Ответ №5

Проблема может быть решена путем настройки пути pylint под venv:
$ cat.vscode/settings.json

{
"python.pythonPath": "venv/bin/python",
"python.linting.pylintPath": "venv/bin/pylint"
}

Ответ №6

Я не знаю, как это работает с WingIDE, но для использования PyLint с Geany я установил внешнюю команду:

PYTHONPATH=${PYTHONPATH}:$(dirname %d) pylint --output-format=parseable --reports=n "%f"

где% f – имя файла, а% d – путь. Может быть полезно кому-то:)

Ответ №7

Мне пришлось обновить переменную system PYTHONPATH, чтобы добавить мой путь к App Engine. В моем случае мне просто пришлось отредактировать файл ~/.bashrc и добавить следующую строку:

export PYTHONPATH=$PYTHONPATH:/path/to/google_appengine_folder

На самом деле, я сначала попытался установить init-hook, но это не помогло решить проблему последовательно по моей базе кода (не знаю почему). Как только я добавил его на системный путь (вероятно, хорошая идея в целом), мои проблемы ушли.

Ответ №8

Один обходной путь, который я только что открыл, – это просто запустить PyLint для всего пакета, а не только одного файла. Так или иначе, ему удастся найти импортированный модуль.

Ответ №9

Попробуйте

if __name__ == '__main__':
    from [whatever the name of your package is] import one
else:
    import one

Обратите внимание, что в Python 3 синтаксис для части в предложении else будет

from .. import one

Забастовкa >

С другой стороны, это, вероятно, не решит вашу конкретную проблему. Я не понял этот вопрос и подумал, что two.py запускается в качестве основного модуля, но это не так. И учитывая различия в способе Python 2.6 (без импорта absolute_import from __future__) и импорта ручек Python 3.x, в любом случае вам не нужно будет делать это для Python 2.6, я не думаю.

Тем не менее, если вы в конечном итоге переключитесь на Python 3 и планируете использовать модуль как пакетный модуль и как автономный script внутри пакета, может быть хорошей идеей сохранить
что-то вроде

if __name__ == '__main__':
    from [whatever the name of your package is] import one   # assuming the package is in the current working directory or a subdirectory of PYTHONPATH
else:
    from .. import one

в виду.

EDIT: И теперь для возможного решения вашей реальной проблемы. Либо запустите PyLint из каталога, содержащего ваш модуль one (возможно, с помощью командной строки), либо поместите следующий код где-нибудь при запуске PyLint:

import os

olddir = os.getcwd()
os.chdir([path_of_directory_containing_module_one])
import one
os.chdir(olddir)

В принципе, в качестве альтернативы возиться с PYTHONPATH, просто убедитесь, что текущий рабочий каталог – это каталог, содержащий one.py, когда вы выполняете импорт.

(Глядя на ответ Брайана, вы, вероятно, могли бы присвоить предыдущий код init_hook, но если вы это сделаете, вы можете просто сделать добавление к sys.path, которое он делает, что немного более элегантно чем мое решение.)

Ответ №10

Ключ состоит в том, чтобы добавить каталог проекта в sys.path без учета переменной env.

Для тех, кто использует VSCode, здесь однострочное решение для вас, если есть базовый каталог вашего проекта:

[MASTER]
init-hook='base_dir="my_spider"; import sys,os,re; _re=re.search(r".+/" + base_dir, os.getcwd()); project_dir = _re.group() if _re else os.path.join(os.getcwd(), base_dir); sys.path.append(project_dir)'

Позвольте мне объяснить это немного:

  • re.search(r".+/" + base_dir, os.getcwd()).group(): найдите базовый каталог в соответствии с файлом редактирования

  • os.path.join(os.getcwd(), base_dir): добавить cwd в sys.path для соответствия среде командной строки


FYI, здесь мой .pylintrc:

https://gist.github.com/chuyik/f0ffc41a6948b6c87c7160151ffe8c2f

Ответ №11

У меня была такая же проблема и я исправил ее, установив pylint в свой virtualenv, а затем добавив файл .pylintrc в каталог проекта со следующим в файле:

[Master]
init-hook='sys.path = list(); sys.path.append("./Lib/site-packages/")'

Ответ №12

Может быть, вручную добавив каталог в PYTHONPATH?

sys.path.append(dirname)

Ответ №13

У меня была такая же проблема, и поскольку я не мог найти ответ, я надеюсь, что это может помочь любому, у кого есть аналогичная проблема.

Я использую flymake с эпилином. В основном то, что я сделал, это добавить привязку в режиме ожидания, которая проверяет, является ли устаревшая директория каталогом пакетов python. Если я добавлю его в PYTHONPATH. В моем случае я считаю, что каталог является пакетом python, если он содержит файл с именем “setup.py”.

;;;;;;;;;;;;;;;;;
;; PYTHON PATH ;;
;;;;;;;;;;;;;;;;;

(defun python-expand-path ()
"Append a directory to the PYTHONPATH."
(interactive
(let ((string (read-directory-name
"Python package directory: "
nil
'my-history)))
(setenv "PYTHONPATH" (concat (expand-file-name string)
(getenv ":PYTHONPATH"))))))

(defun pythonpath-dired-mode-hook ()
(let ((setup_py (concat default-directory "setup.py"))
(directory (expand-file-name default-directory)))
;;   (if (file-exists-p setup_py)
(if (is-python-package-directory directory)
(let ((pythonpath (concat (getenv "PYTHONPATH") ":"
(expand-file-name directory))))
(setenv "PYTHONPATH" pythonpath)
(message (concat "PYTHONPATH=" (getenv "PYTHONPATH")))))))

(defun is-python-package-directory (directory)
(let ((setup_py (concat directory "setup.py")))
(file-exists-p setup_py)))

(add-hook 'dired-mode-hook 'pythonpath-dired-mode-hook)

Надеюсь, что это поможет.

Ответ №14

Если кто-то ищет способ запустить pylint в качестве внешнего инструмента в PyCharm и работать с виртуальными средами (почему я пришел к этому вопросу), вот как я его решил:

  • В PyCharm > Настройки > Инструменты > Внешние инструменты, добавьте или отредактируйте элемент для pylint.
  • В диалоговом окне “Инструменты” диалогового окна “Редактировать инструмент” установите “Программа” на использование pylint из каталога интерпретатора python: $PyInterpreterDirectory$/pylint
  • Задайте другие параметры в поле “Параметры”, например: --rcfile=$ProjectFileDir$/pylintrc -r n $FileDir$
  • Установите рабочий каталог $FileDir$

Теперь, используя pylint в качестве внешнего инструмента, запустите pylint в любом каталоге, который вы выбрали, используя общий файл конфигурации и используя любой интерпретатор, настроенный для вашего проекта (который предположительно является вашим интерпретатором virtualenv).

Ответ №15

Я нашел хороший ответ от https://sam.hooke.me/note/2019/01/call-python-script-from-pylint-init-hook/
отредактируйте ваш pylintrc и добавьте следующее в master init-hook="import imp, os; from pylint.config import find_pylintrc; imp.load_source('import_hook', os.path.join(os.path.dirname(find_pylintrc()), 'import_hook.py'))"

Ответ №16

если вы используете vscode, убедитесь, что каталог вашего пакета находится вне каталога _pychache__.

Ответ №17

Это старый вопрос, но нет принятого ответа, поэтому я предлагаю: измените оператор импорта в two.py, чтобы он читался следующим образом:

from .. import one

В моей текущей среде (Python 3.6, VSCode использует pylint 2.3.1) это очищает помеченный оператор.

Ответ №18

Если вы используете Cython в Linux, я решил удалить файлы module.cpython-XXm-X-linux-gnu.so из целевой директории моего проекта.

Ответ №19

Здравствуйте, я смог импортировать пакеты из другого каталога. Я просто сделал следующее:
Примечание. Я использую VScode

Шаги для создания пакета Python
Работать с пакетами Python действительно просто. Все, что вам нужно сделать, это:

Создайте каталог и дайте ему имя вашего пакета.
Поместите свои классы в это.
Создайте файл init.py в каталоге

.Например: у вас есть папка с именем Framework, в которой вы храните все пользовательские классы, и ваша задача – просто создать файл init.py внутри папки с именем Framework.

И при импорте вам нужно импортировать в этот fashion—>

из базы импорта Framework

так что ошибка E0401 исчезает
Framework – это папка, в которой вы только что создали init.py и
base – ваш пользовательский модуль, в который вы должны импортировать и работать над
Надеюсь, это поможет!!!!

Environment data

  • VS Code version: 1.20.0
  • Extension version (available under the Extensions sidebar): 2018.2.1
  • OS and version: macOS Sierra version 10.12.6
  • Python version (& distribution if applicable, e.g. Anaconda): Anaconda custom (64 bit) Python 3.6.4
  • Type of virtual environment used (N/A | venv | virtualenv | conda | …): conda
  • Relevant/affected Python packages and their versions:

pylint_error

user_settings

workspace_settings

Actual behavior

This program works fine from the command line. I wrote this using the Python extension approx. 6 months ago on another mac. I recently picked up this program again and it shows me the import errors as shown in the attached screenshot. I know that it is pylint related. I am also attaching my user settings and workspace settings screenshots

Expected behavior

It should not show errors for import

Steps to reproduce:

See the screenshorts

Logs

Output for Python in the Output panel (ViewOutput, change the drop-down the upper-right of the Output panel to Python)

6,0,error,E0401:Unable to import ‘vglabs_common’
7,0,error,E0401:Unable to import ‘vglabs_anis’
8,0,error,E0401:Unable to import ‘vglabs_brz’
10,0,error,E0401:Unable to import ‘vglabs_inf’
11,0,error,E0401:Unable to import ‘vglabs_mrp’
12,0,error,E0401:Unable to import ‘vglabs_nmr’
13,0,error,E0401:Unable to import ‘vglabs_op’
14,0,error,E0401:Unable to import ‘vglabs_re’
15,0,error,E0401:Unable to import ‘vglabs_ssk’
16,0,error,E0401:Unable to import ‘vglabs_txc’
17,0,error,E0401:Unable to import ‘vglabs_xrd’
##########Linting Output — pylint##########
No config file found, using default configuration
************* Module vglabs_uploader
6,0,error,E0401:Unable to import ‘vglabs_common’
7,0,error,E0401:Unable to import ‘vglabs_anis’
8,0,error,E0401:Unable to import ‘vglabs_brz’
10,0,error,E0401:Unable to import ‘vglabs_inf’
11,0,error,E0401:Unable to import ‘vglabs_mrp’
12,0,error,E0401:Unable to import ‘vglabs_nmr’
13,0,error,E0401:Unable to import ‘vglabs_op’
14,0,error,E0401:Unable to import ‘vglabs_re’
15,0,error,E0401:Unable to import ‘vglabs_ssk’
16,0,error,E0401:Unable to import ‘vglabs_txc’
17,0,error,E0401:Unable to import ‘vglabs_xrd’
59,0,refactor,R0912:Too many branches (15/12)
107,0,refactor,R0912:Too many branches (15/12)
5,0,warning,W0611:Unused import psycopg2
XXX


Output from `Console` under the `Developer Tools` panel (toggle Developer Tools on under `Help`)

XXX

How do I resolve the «Unable to import module» error that I receive when I run Lambda code in Python?

Last updated: 2022-04-12

I receive an «Unable to import module» error when I try to run my AWS Lambda code in Python. How do I resolve the error?

Short description

You typically receive this error when your Lambda environment can’t find the specified library in the Python code. This is because Lambda isn’t prepackaged with all Python libraries.

To resolve this error, create a deployment package or Lambda layer that includes the libraries that you want to use in your Python code for Lambda.

Important: Make sure that you put the library that you import for Python inside the /python folder.

Resolution

Note: The following steps show you how to create a Lambda layer rather than a deployment package. This is because you can reuse the Lambda layer across multiple Lambda functions. Each Lambda runtime adds specific /opt directory folders to the PATH variable. If the layer uses the same folder structure, then your Lambda function’s code can access the layer content without specifying the path.

It’s a best practice to create a Lambda layer on the same operating system that your Lambda runtime is based on. For example, Python 3.8 is based on an Amazon Linux 2 Amazon Machine Image (AMI). However, Python 3.7 and Python 3.6 are based on the Amazon Linux AMI.

To create a Lambda layer for a Python 3.8 library, do the following:

1.    In the AWS Cloud9 console, create an Amazon Elastic Compute Cloud (Amazon EC2) instance with Amazon Linux 2 AMI. For instructions, see Creating an EC2 environment in the AWS Cloud9 User Guide.

2.    Create an AWS Identity and Access Management (IAM) policy that grants permissions to call the PublishLayerVersion API operation.

Example IAM policy statement that grants permissions to call the PublishLayerVersion API operation

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "lambda:PublishLayerVersion",
            "Resource": "*"
        }
    ]
}
$ sudo amazon-linux-extras install python3.8
$ curl -O https://bootstrap.pypa.io/get-pip.py
$ python3.8 get-pip.py --user

5.    Create a python folder by running the following command:

6.    Install the Pandas library files into the python folder by running the following command:

Important: Replace Pandas with the name of the Python library that you want to import.

$ python3.8 -m pip install pandas -t python/

7.    Zip the contents of the python folder into a layer.zip file by running the following command:

$ zip -r layer.zip python

8.    Publish the Lambda layer by running the following command:

Important: Replace us-east-1 with the AWS Region that your Lambda function is in.

$ aws lambda publish-layer-version --layer-name pandas-layer --zip-file fileb://layer.zip --compatible-runtimes python3.8 --region us-east-1


Did this article help?


Do you need billing or technical support?

AWS support for Internet Explorer ends on 07/31/2022. Supported browsers are Chrome, Firefox, Edge, and Safari.
Learn more »

Пытаться

if __name__ == '__main__':
    from [whatever the name of your package is] import one
else:
    import one

Обратите внимание, что в Python 3 синтаксис для части в else пункт будет

from .. import one

Если подумать, это, вероятно, не решит вашу конкретную проблему. Я неправильно понял вопрос и подумал, что two.py запускается как основной модуль, но это не так. И учитывая различия в способах Python 2.6 (без импорта absolute_import от __future__) и Python 3.x обрабатывают импорт, вам в любом случае не нужно делать это для Python 2.6, я не думаю.

Тем не менее, если вы в конечном итоге переключитесь на Python 3 и планируете использовать модуль как в качестве модуля пакета, так и в качестве автономного скрипта внутри пакета, может быть хорошей идеей сохранить что-то вроде

if __name__ == '__main__':
    from [whatever the name of your package is] import one   # assuming the package is in the current working directory or a subdirectory of PYTHONPATH
else:
    from .. import one

в виду.

РЕДАКТИРОВАТЬ: А теперь о возможном решении вашей реальной проблемы. Либо запустите PyLint из каталога, содержащего ваш one модуль (возможно, через командную строку) или поместите где-нибудь следующий код при запуске PyLint:

import os

olddir = os.getcwd()
os.chdir([path_of_directory_containing_module_one])
import one
os.chdir(olddir)

По сути, в качестве альтернативы возиться с PYTHONPATH просто убедитесь, что текущий рабочий каталог — это каталог, содержащий one.py когда вы делаете импорт.

(Глядя на ответ Брайана, вы, вероятно, могли бы присвоить предыдущий код init_hook, но если вы собираетесь это сделать, вы можете просто добавить к sys.path что он делает, что немного более элегантно, чем мое решение.)


Я запускаю PyLint изнутри Wing IDE на Windows. У меня есть подкаталог (пакет) в моем проекте, и внутри пакета я импортирую модуль с верхнего уровня, т.е.

__init__.py
myapp.py
one.py
subdir
    __init__.py
    two.py

Внутри у two.pyменя есть, import oneи это прекрасно работает во время выполнения, потому что каталог верхнего уровня (из которого myapp.pyзапускается) находится в пути Python. Однако, когда я запускаю PyLint на two.py, он выдает ошибку:

F0401: Unable to import 'one'

Как это исправить?

Ответы:


Есть два варианта, которые я знаю.

Во-первых, измените PYTHONPATHпеременную среды, чтобы она включала каталог над вашим модулем.

Или отредактируйте, ~/.pylintrcчтобы включить каталог над вашим модулем, например так:

[MASTER]
init-hook='import sys; sys.path.append("/path/to/root")'

(Или в другой версии pylint, init-hook требует от вас изменить [General] на [MASTER])

Оба эти варианта должны работать.

Надеюсь, это поможет.







Решение по изменению пути init-hook— это хорошо, но мне не нравится тот факт, что мне пришлось добавить туда абсолютный путь, так как в результате я не могу поделиться этим файлом pylintrc среди разработчиков проекта. Это решение, использующее относительный путь к файлу pylintrc, работает лучше для меня:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

Обратите внимание, что pylint.config.PYLINTRCтакже существует и имеет то же значение, что и find_pylintrc().





1) sys.path — это список.

2) Иногда проблема в том, что sys.path не является вашим virtualenv.path, и вы хотите использовать pylint в вашем virtualenv.

3) Как и сказано, используйте init-hook (обратите внимание на ‘и «синтаксический анализ pylint)

[Master]
init-hook='sys.path = ["/path/myapps/bin/", "/path/to/myapps/lib/python3.3/site-packages/", ... many paths here])'

или

[Master]
init-hook='sys.path = list(); sys.path.append("/path/to/foo")'

.. и

pylint --rcfile /path/to/pylintrc /path/to/module.py




Проблема может быть решена путем настройки пути pylint под venv: $ cat .vscode / settings.json

{
    "python.pythonPath": "venv/bin/python",
    "python.linting.pylintPath": "venv/bin/pylint"
}





У вас есть пустой __init__.pyфайл в обоих каталогах, чтобы python знал, что каталоги являются модулями?

Основная схема, когда вы не запускаете из папки (то есть, возможно, из Pylint, хотя я не использовал это):

topdir
  __init__.py
  functions_etc.py
  subdir
    __init__.py
    other_functions.py

Это то, как интерпретатор Python узнает о модуле без ссылки на текущий каталог, поэтому, если Pylint работает по своему собственному абсолютному пути, он сможет получить доступ functions_etc.pyкак topdir.functions_etcили topdir.subdir.other_functions, если он topdirнаходится в PYTHONPATH.

ОБНОВЛЕНИЕ: Если проблема не в __init__.pyфайле, возможно просто попробуйте скопировать или переместить ваш модуль в c:Python26Libsite-packages— это обычное место для размещения дополнительных пакетов, и он обязательно будет в вашем pythonpath. Если вы знаете, как создавать символические ссылки Windows или аналогичные (я не знаю!), Вы можете сделать это вместо этого. Здесь есть еще много вариантов : http://docs.python.org/install/index.html , включая возможность добавления sys.path к каталогу пользовательского уровня вашего кода разработки, но на практике я обычно просто символически связываю мой локальный каталог разработки для пакетов сайта — копирование его имеет тот же эффект.






общий ответ на этот вопрос, который я нашел на этой странице, пожалуйста, не открыт, сайт ошибся

создать .pylintrcи добавить

[MASTER]
init-hook="from pylint.config import find_pylintrc;
import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"


Я не знаю, как это работает с WingIDE, но для использования PyLint с Geany я установил свою внешнюю команду на:

PYTHONPATH=${PYTHONPATH}:$(dirname %d) pylint --output-format=parseable --reports=n "%f"

где% f — имя файла, а% d — путь. Может быть кому-то пригодится :)


Мне пришлось обновить системную PYTHONPATHпеременную, чтобы добавить мой путь к App Engine. В моем случае мне просто нужно было отредактировать мой ~/.bashrcфайл и добавить следующую строку:

export PYTHONPATH=$PYTHONPATH:/path/to/google_appengine_folder

На самом деле, я попытался установить init-hookпервый, но это не помогло решить проблему во всей моей кодовой базе (не знаю почему). Как только я добавил его в системный путь (вероятно, хорошая идея в целом), мои проблемы исчезли.


Один из обходных путей, который я только что обнаружил, — это просто запустить PyLint для всего пакета, а не для одного файла. Каким-то образом удается найти импортированный модуль.




Пытаться

if __name__ == '__main__':
    from [whatever the name of your package is] import one
else:
    import one

Обратите внимание, что в Python 3 синтаксис для части в else предложении будет

from .. import one

Если подумать, это, вероятно, не решит вашу конкретную проблему. Я неправильно понял вопрос и подумал, что two.py запускается как основной модуль, но это не так. И учитывая различия в способе Python 2.6 (без импорта absolute_importиз__future__ ) и Python 3.x, в любом случае вам не понадобится делать это для Python 2.6, я не думаю.

Тем не менее, если вы в конечном итоге переключитесь на Python 3 и планируете использовать модуль как пакетный модуль и как отдельный скрипт внутри пакета, возможно, будет хорошей идеей сохранить что-то вроде

if __name__ == '__main__':
    from [whatever the name of your package is] import one   # assuming the package is in the current working directory or a subdirectory of PYTHONPATH
else:
    from .. import one

в уме.

РЕДАКТИРОВАТЬ: И теперь для возможного решения вашей актуальной проблемы. Либо запустите PyLint из каталога, содержащего ваш oneмодуль (возможно, из командной строки), либо поместите следующий код где-нибудь при запуске PyLint:

import os

olddir = os.getcwd()
os.chdir([path_of_directory_containing_module_one])
import one
os.chdir(olddir)

В основном, в качестве альтернативы возни с PYTHONPATH, просто убедитесь, что текущий рабочий каталог — это каталог, содержащий one.py при выполнении импорта.

(Глядя на ответ Брайана, вы, вероятно, могли бы присвоить предыдущий код init_hook, но если вы собираетесь это сделать, то можете просто добавить к нему sys.pathто, что он делает, что несколько элегантнее, чем мое решение.)


Ключ должен добавить каталог вашего проекта в sys.path без учета переменной env.

Для тех, кто использует VSCode, вот решение для одной строки, если есть базовый каталог вашего проекта:

[MASTER]
init-hook='base_dir="my_spider"; import sys,os,re; _re=re.search(r".+/" + base_dir, os.getcwd()); project_dir = _re.group() if _re else os.path.join(os.getcwd(), base_dir); sys.path.append(project_dir)'

Позвольте мне объяснить это немного:

  • re.search(r".+/" + base_dir, os.getcwd()).group(): найти базовый каталог в соответствии с файлом редактирования

  • os.path.join(os.getcwd(), base_dir): добавить, cwdчтобы sys.pathсоответствовать среде командной строки


К вашему сведению, вот мой .pylintrc:

https://gist.github.com/chuyik/f0ffc41a6948b6c87c7160151ffe8c2f


У меня была та же проблема, и я исправил ее, установив pylint в моем virtualenv, а затем добавив файл .pylintrc в каталог моего проекта, добавив в него следующее:

[Master]
init-hook='sys.path = list(); sys.path.append("./Lib/site-packages/")'



Может быть, вручную добавив dir в PYTHONPATH?

sys.path.append(dirname)





У меня была такая же проблема, и так как я не мог найти ответ, я надеюсь, что это может помочь любому с подобной проблемой.

Я использую мухи с эпилинтом. По сути, я добавил хук dired-mode, который проверял, является ли каталог dired каталогом пакета python. Если это так, я добавляю его в PYTHONPATH. В моем случае я считаю каталог пакетом Python, если он содержит файл с именем «setup.py».

;;;;;;;;;;;;;;;;;
;; PYTHON PATH ;;
;;;;;;;;;;;;;;;;;

(defun python-expand-path ()
  "Append a directory to the PYTHONPATH."
  (interactive
   (let ((string (read-directory-name 
          "Python package directory: " 
          nil 
          'my-history)))
     (setenv "PYTHONPATH" (concat (expand-file-name string)
                  (getenv ":PYTHONPATH"))))))

(defun pythonpath-dired-mode-hook ()
  (let ((setup_py (concat default-directory "setup.py"))
    (directory (expand-file-name default-directory)))
    ;;   (if (file-exists-p setup_py)
    (if (is-python-package-directory directory)
    (let ((pythonpath (concat (getenv "PYTHONPATH") ":" 
                  (expand-file-name directory))))
      (setenv "PYTHONPATH" pythonpath)
      (message (concat "PYTHONPATH=" (getenv "PYTHONPATH")))))))

(defun is-python-package-directory (directory)
  (let ((setup_py (concat directory "setup.py")))
    (file-exists-p setup_py)))

(add-hook 'dired-mode-hook 'pythonpath-dired-mode-hook)

Надеюсь это поможет.


Если кто-то ищет способ запустить Pylint как внешний инструмент в PyCharm и заставить его работать со своими виртуальными средами (почему я пришел к этому вопросу), вот как я решил это:

  1. В PyCharm> «Настройки»> «Инструменты»> «Внешние инструменты» добавьте или измените элемент для столбца.
  2. В настройках инструмента диалогового окна «Редактировать инструмент» задайте для программы использование pylint из каталога интерпретатора python: $PyInterpreterDirectory$/pylint
  3. Установите другие параметры в поле «Параметры», например: --rcfile=$ProjectFileDir$/pylintrc -r n $FileDir$
  4. Установите ваш рабочий каталог на $FileDir$

Теперь использование pylint в качестве внешнего инструмента будет запускать pylint в любом каталоге, который вы выбрали, используя общий файл конфигурации, и использовать любой интерпретатор, настроенный для вашего проекта (который, вероятно, является вашим интерпретатором virtualenv).


Это старый вопрос, но нет принятого ответа, поэтому я предлагаю: измените оператор импорта в two.py, чтобы он читался так:

from .. import one

В моей текущей среде (Python 3.6, VSCode с использованием pylint 2.3.1) это очищает помеченный оператор.


Я нашел хороший ответ . Отредактируйте ваш pylintrc и добавьте следующее в master

init-hook="import imp, os; from pylint.config import find_pylintrc; imp.load_source('import_hook', os.path.join(os.path.dirname(find_pylintrc()), 'import_hook.py'))"


Когда вы устанавливаете Python, вы можете настроить путь. Если путь уже определен, то, что вы можете сделать, находится в VS Code, нажмите Ctrl + Shift + P и введите Python: выберите Interpreter и выберите обновленную версию Python. Перейдите по этой ссылке для получения дополнительной информации, https://code.visualstudio.com/docs/python/environments


если вы используете vscode, убедитесь, что каталог вашего пакета находится вне каталога _pychache__.



Если вы используете Cython в Linux, я решил удалить module.cpython-XXm-X-linux-gnu.soфайлы из целевой директории моего проекта.


просто добавьте этот код в файл .vscode / settings.json

, «python.linting.pylintPath»: «venv / bin / pylint»

Это сообщит местоположение pylint (который является средством проверки ошибок для python)


Здравствуйте, я смог импортировать пакеты из другого каталога. Я просто сделал следующее: Примечание: я использую VScode

Шаги для создания пакета Python Работать с пакетами Python действительно просто. Все, что вам нужно сделать, это:

Создайте каталог и дайте ему имя вашего пакета. Поместите свои классы в это. Создайте файл init .py в каталоге

Например: у вас есть папка с именем Framework, в которой вы храните все пользовательские классы, и ваша задача — просто создать файл init .py внутри папки с именем Framework.

И при импорте нужно импортировать таким образом —>

из базы импорта Framework

ошибка E0401 исчезает. Framework — это папка, в которой вы только что создали init .py, а base — ваш пользовательский модуль, в который вы должны импортировать и работать над ним. Надеюсь, это поможет !!!!

Igor

Новичок

Пользователь

  • #1

Модуль импортируется, доступ к содержимому есть.
И все равно подчеркивает import — Unable to import ‘util_date’pylint(import-error)

Python:

import sys
import os
sys.path.append(os.path.join(sys.path[0], '..util'))
from datetime import date
import util_date

ОС win10
python 3.8
ide VScode

Student

Student

throw exception

Команда форума

Администратор

  • #2

Может быть так:

Python:

from util import util_date

1. Unable to import (pylint)

  • Scenario: You have a module installed, however the linter in the IDE is complaining about; not being able to import the module, hence error messages such as the following are displayed as linter errors:
.. unable to import 'xxx' .. 
  • Cause: The Python extension is most likely using the wrong version of Pylint.

Solution 1: (configure workspace settings to point to fully qualified python executable):

  1. Open the workspace settings (settings.json)
  2. Identify the fully qualified path to the python executable (this could even be a virtual environment)
  3. Ensure Pylint is installed for the above python environment
  4. Configure the setting “pythonPath” to point to (previously identified) the fully qualified python executable.
"python.pythonPath": "/users/xxx/bin/python"

Solution 2: (open VS Code from an activated virtual environment):

  1. Open the terminal window
  2. Activate the relevant python virtual environment
  3. Ensure Pylint is installed within this virtual environment pip install pylint
  4. Close all instances of VS Code
  5. Launch VS Code from within this terminal window
    (this will ensure the VS Code process will inherit all of the Virtual Env environment settings)

2. Linting with xxx failed. …

Listing could fail due to a number of reasons. Please check each of the following.

Cause: The path to the python executable is incorrect
Solution: Configure the path to the python executable in the settings.json

Cause: The linter has not been installed in the Python environment being used
Solution: Identify the Python environment (executable) configured in settings.json. Next install the linter(s) against this Python environment (use the corresponding Pip).

Cause: The Path to the linter is incorrect
Solution: If you have provided a custom path to the linter in settings.json, then ensure this file path exist.

For further information on configuring Linters can be found here.

3. Ignore certain messages

It is possible you would like to ignore certain linter messages. This could be done easily.
Generally most linters support configuration files, hence all you need to do is create the relevant configuration file and ignore the appropriate error message.
If on the other hand the linters support the ability to ignore certain messages via command line args, this can be done as well.

Solution: Add relevant command line args to ignore certain messages
Here we’ll assume you use a TAB character as indentation of python code instead of 4 or 2 spaces.
Pylint would generally display a warning for this with the error code W0312.
In order to disable this particular message all one needs to do is as follows in the settings.json file:

 "python.linting.pylintArgs": [
        "--disable=W0312"
 ],

Note: You could apply the above configuration settings in your user settings file, so that it applies to all workspaces.
This saves you from having to define these settings for every single workspace (every time).

For further information on configuring Linters can be found here.

Содержание

  1. Linting
  2. 1. Unable to import (pylint)
  3. 2. Linting with xxx failed. …
  4. 3. Ignore certain messages
  5. Linting
  6. 1. Unable to import (pylint)
  7. 2. Linting with xxx failed. …
  8. 3. Ignore certain messages
  9. Linting Python in Visual Studio Code
  10. Enable linting
  11. Disable linting
  12. Run linting
  13. General linting settings
  14. Specific linters
  15. Pylint
  16. Command-line arguments and configuration files
  17. pydocstyle
  18. Command-line arguments and configuration files
  19. Message category mapping
  20. pycodestyle (pep8)
  21. Command-line arguments and configuration files
  22. Message category mapping
  23. Prospector
  24. Command-line arguments and configuration files
  25. Message category mapping
  26. Flake8
  27. Command-line arguments and configuration files
  28. Message category mapping
  29. Message category mapping

Linting

1. Unable to import (pylint)

  • Scenario: You have a module installed, however the linter in the IDE is complaining about; not being able to import the module, hence error messages such as the following are displayed as linter errors:
  • Cause: The Python extension is most likely using the wrong version of Pylint.

Solution 1: (configure workspace settings to point to fully qualified python executable):

  1. Open the workspace settings (settings.json)
  2. Identify the fully qualified path to the python executable (this could even be a virtual environment)
  3. Ensure Pylint is installed for the above python environment
  4. Configure the setting “pythonPath” to point to (previously identified) the fully qualified python executable.

Solution 2: (open VS Code from an activated virtual environment):

  1. Open the terminal window
  2. Activate the relevant python virtual environment
  3. Ensure Pylint is installed within this virtual environment pip install pylint
  4. Close all instances of VS Code
  5. Launch VS Code from within this terminal window
    (this will ensure the VS Code process will inherit all of the Virtual Env environment settings)

2. Linting with xxx failed. …

Listing could fail due to a number of reasons. Please check each of the following.

Cause: The path to the python executable is incorrect
Solution: Configure the path to the python executable in the settings.json

Cause: The linter has not been installed in the Python environment being used
Solution: Identify the Python environment (executable) configured in settings.json. Next install the linter(s) against this Python environment (use the corresponding Pip).

Cause: The Path to the linter is incorrect
Solution: If you have provided a custom path to the linter in settings.json, then ensure this file path exist.

For further information on configuring Linters can be found here.

3. Ignore certain messages

It is possible you would like to ignore certain linter messages. This could be done easily.
Generally most linters support configuration files, hence all you need to do is create the relevant configuration file and ignore the appropriate error message.
If on the other hand the linters support the ability to ignore certain messages via command line args, this can be done as well.

Solution: Add relevant command line args to ignore certain messages
Here we’ll assume you use a TAB character as indentation of python code instead of 4 or 2 spaces. Pylint would generally display a warning for this with the error code W0312.
In order to disable this particular message all one needs to do is as follows in the settings.json file:

Note: You could apply the above configuration settings in your user settings file, so that it applies to all workspaces.
This saves you from having to define these settings for every single workspace (every time).

For further information on configuring Linters can be found here.

Linting

1. Unable to import (pylint)

  • Scenario: You have a module installed, however the linter in the IDE is complaining about; not being able to import the module, hence error messages such as the following are displayed as linter errors:
  • Cause: The Python extension is most likely using the wrong version of Pylint.

Solution 1: (configure workspace settings to point to fully qualified python executable):

  1. Open the workspace settings (settings.json)
  2. Identify the fully qualified path to the python executable (this could even be a virtual environment)
  3. Ensure Pylint is installed for the above python environment
  4. Configure the setting “pythonPath” to point to (previously identified) the fully qualified python executable.

Solution 2: (open VS Code from an activated virtual environment):

  1. Open the terminal window
  2. Activate the relevant python virtual environment
  3. Ensure Pylint is installed within this virtual environment pip install pylint
  4. Close all instances of VS Code
  5. Launch VS Code from within this terminal window
    (this will ensure the VS Code process will inherit all of the Virtual Env environment settings)

2. Linting with xxx failed. …

Listing could fail due to a number of reasons. Please check each of the following.

Cause: The path to the python executable is incorrect
Solution: Configure the path to the python executable in the settings.json

Cause: The linter has not been installed in the Python environment being used
Solution: Identify the Python environment (executable) configured in settings.json. Next install the linter(s) against this Python environment (use the corresponding Pip).

Cause: The Path to the linter is incorrect
Solution: If you have provided a custom path to the linter in settings.json, then ensure this file path exist.

For further information on configuring Linters can be found here.

3. Ignore certain messages

It is possible you would like to ignore certain linter messages. This could be done easily.
Generally most linters support configuration files, hence all you need to do is create the relevant configuration file and ignore the appropriate error message.
If on the other hand the linters support the ability to ignore certain messages via command line args, this can be done as well.

Solution: Add relevant command line args to ignore certain messages
Here we’ll assume you use a TAB character as indentation of python code instead of 4 or 2 spaces. Pylint would generally display a warning for this with the error code W0312.
In order to disable this particular message all one needs to do is as follows in the settings.json file:

Note: You could apply the above configuration settings in your user settings file, so that it applies to all workspaces.
This saves you from having to define these settings for every single workspace (every time).

For further information on configuring Linters can be found here.

Источник

Linting Python in Visual Studio Code

Linting highlights syntactical and stylistic problems in your Python source code, which often helps you identify and correct subtle programming errors or unconventional coding practices that can lead to errors. For example, linting detects use of an uninitialized or undefined variable, calls to undefined functions, missing parentheses, and even more subtle issues such as attempting to redefine built-in types or functions. Linting is thus distinct from Formatting because linting analyzes how the code runs and detects errors whereas formatting only restructures how code appears.

Note: Stylistic and syntactical code detection is enabled by the Language Server. To enable third-party linters for additional problem detection, you can enable them by using the Python: Select Linter command and selecting the appropriate linter.

Enable linting

To enable linters, open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and select the Python: Select Linter command. The Select Linter command adds «python.linting.

  • Enabled»: true to your settings, where
  • is the name of the chosen linter. See Specific linters for details.

    Enabling a linter prompts you to install the required packages in your selected environment for the chosen linter.

    Note: If you’re using a global environment and VS Code is not running elevated, linter installation may fail. In that case, either run VS Code elevated, or manually run the Python package manager to install the linter at an elevated command prompt for the same environment: for example sudo pip3 install pylint (macOS/Linux) or pip install pylint (Windows, at an elevated prompt).

    Disable linting

    You can easily toggle between enabling and disabling your linter. To switch, open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and select the Python: Enable/Disable Linting command.

    This will populate a dropdown with the current linting state and options to Enable or Disable Python linting.

    Run linting

    To perform linting, open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), filter on «linting», and select Python: Run Linting. Linting will run automatically when you save a file.

    Issues are shown in the Problems panel and as wavy underlines in the code editor. Hovering over an underlined issue displays the details:

    General linting settings

    You can add any of the linting settings to your user settings.json file (opened with the File > Preferences > Settings command ⌘, (Windows, Linux Ctrl+, ) ). Refer to User and Workspace settings to find out more about working with settings in VS Code.

    To change the linting behavior across all enabled linters, modify the following settings:

    Feature Setting
    (python.linting.)
    Default value
    Linting in general enabled true
    Linting on file save lintOnSave true
    Maximum number of linting messages maxNumberOfProblems 100
    Exclude file and folder patterns ignorePatterns [«.vscode/*.py», «**/site-packages/**/*.py»]

    When enabling lintOnSave , you might also want to enable the generic files.autoSave option (see Save / Auto Save). The combination provides frequent linting feedback in your code as you type.

    Specific linters

    The following table provides a summary of available Python linters and their basic settings. For descriptions of individual settings, see the Linter settings reference.

    Linter Package name for pip install command True/false enable setting
    (python.linting.)
    Arguments setting
    (python.linting.)
    Custom path setting
    (python.linting.)
    Pylint pylint pylintEnabled pylintArgs pylintPath
    Flake8 flake8 flake8Enabled flake8Args flake8Path
    mypy mypy mypyEnabled mypyArgs mypyPath
    pycodestyle (pep8) pycodestyle pycodestyleEnabled pycodestyleArgs pycodestylePath
    prospector prospector prospectorEnabled prospectorArgs prospectorPath
    pylama pylama pylamaEnabled pylamaArgs pylamaPath
    bandit bandit banditEnabled banditArgs banditPath

    Note: If you don’t find your preferred linter in the table above, you can add support via an extension. The Python Extension Template makes it easy to integrate new Python tools into VS Code.

    To select a different linter, use the Python: Select Linter command. You can also edit your settings manually to enable multiple linters. Note, that using the Select Linter command overwrites those edits.

    Custom arguments are specified in the appropriate arguments setting for each linter. Each top-level element of an argument string that’s separated by a space on the command line must be a separate item in the args list. For example:

    If a top-level element is a single value (delineated by quotation marks or braces), it still appears as a single item in the list even if the value itself contains spaces.

    A custom path is generally unnecessary as the Python extension resolves the path to the linter based on the Python interpreter being used (see Environments). To use a different version of a linter, specify its path in the appropriate custom path setting. For example, if your selected interpreter is a virtual environment but you want to use a linter that’s installed in a global environment, then set the appropriate path setting to point to the global environment’s linter.

    Note: The following sections provide additional details for the individual linters linked in the Specific linters table above. In general, custom rules must be specified in a separate file as required by the linter you’re using.

    Pylint messages fall into the categories in the following table with the indicated mapping to VS Code categories. You can change the setting to change the mapping.

    Pylint category Description VS Code category mapping Applicable setting
    (python.linting.)
    Convention (C) Programming standard violation Information (underline) pylintCategorySeverity.convention
    Refactor (R) Bad code smell Hint (light bulbs) pylintCategorySeverity.refactor
    Warning (W) Python-specific problems Warning pylintCategorySeverity.warning
    Error (E) Likely code bugs Error (underline) pylintCategorySeverity.error
    Fatal (F) An error prevented further Pylint processing Error pylintCategorySeverity.fatal

    Command-line arguments and configuration files

    You can easily generate an options file using different methods. See Pylint command-line arguments for general switches.

    If you’re using command-line arguments:

    Command-line arguments can be used to load Pylint plugins, such as the plugin for Django:

    If you’re using a pylintrc file:

    Options can also be specified in a pylintrc or .pylintrc options file in the workspace folder, as described on Pylint command line arguments.

    To control which Pylint messages are shown, add the following contents to an options file:

    If you’re using Pylint:

    You can create an options file using Pylint itself, by running the command below.

    If you are running Pylint in PowerShell, you have to explicitly specify a UTF-8 output encoding. This file contains sections for all the Pylint options, along with documentation in the comments.

    pydocstyle

    Command-line arguments and configuration files

    See pydocstyle Command Line Interface for general options. For example, to ignore error D400 (first line should end with a period), add the following line to your settings.json file:

    A code prefix also instructs pydocstyle to ignore specific categories of errors. For example, to ignore all Docstring Content issues (D4XXX errors), add the following line to settings.json :

    More details can be found in the pydocstyle documentation.

    Options can also be read from a [pydocstyle] section of any of the following configuration files:

    • setup.cfg
    • tox.ini
    • .pydocstyle
    • .pydocstyle.ini
    • .pydocstylerc
    • .pydocstylerc.ini

    For more information, see Configuration Files.

    Message category mapping

    The Python extension maps all pydocstyle errors to the Convention (C) category.

    pycodestyle (pep8)

    Command-line arguments and configuration files

    See pycodestyle example usage and output for general switches. For example, to ignore error E303 (too many blank lines), add the following line to your settings.json file:

    pycodestyle options are read from the [pycodestyle] section of a tox.ini or setup.cfg file located in any parent folder of the path(s) being processed. For details, see pycodestyle configuration.

    Message category mapping

    The Python extension maps pycodestyle message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.

    pycodestyle category Applicable setting
    (python.linting.)
    VS Code category mapping
    W pycodestyleCategorySeverity.W Warning
    E pycodestyleCategorySeverity.E Error

    Prospector

    Command-line arguments and configuration files

    See Prospector Command Line Usage for general options. For example, to set a strictness level of «very high,» add the following line to your settings.json file:

    It’s common with Prospector to use profiles to configure how Prospector runs. By default, Prospector loads the profile from a .prospector.yaml file in the current folder.

    Because Prospector calls other tools, such as Pylint, any configuration files for those tools override tool-specific settings in .prospector.yaml . For example, suppose you specify the following, in .prospector.yaml :

    If you also have a .pylintrc file that enables the too-many-arguments warning, you continue to see the warning from Pylint within VS Code.

    Message category mapping

    The Python extension maps all Prospector errors and warnings to the Error (E) category.

    Flake8

    Command-line arguments and configuration files

    See Invoking Flake8 for general switches. For example, to ignore error E303 (too many blank lines), use the following setting:

    By default, Flake8 ignores E121, E123, E126, E226, E24, and E704.

    Flake8 user options are read from the C:Users .flake8 (Windows) or

    /.config/flake8 (macOS/Linux) file.

    At the project level, options are read from the [flake8] section of a tox.ini , setup.cfg , or .flake8 file.

    Message category mapping

    The Python extension maps flake8 message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.

    Flake8 category Applicable setting
    (python.linting.)
    VS Code category mapping
    F flake8CategorySeverity.F Error
    E flake8CategorySeverity.E Error
    W flake8CategorySeverity.W Warning

    Message category mapping

    The Python extension maps mypy message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.

    Источник

  • Environment data

    • VS Code version: 1.20.0
    • Extension version (available under the Extensions sidebar): 2018.2.1
    • OS and version: macOS Sierra version 10.12.6
    • Python version (& distribution if applicable, e.g. Anaconda): Anaconda custom (64 bit) Python 3.6.4
    • Type of virtual environment used (N/A | venv | virtualenv | conda | …): conda
    • Relevant/affected Python packages and their versions:

    pylint_error

    user_settings

    workspace_settings

    Actual behavior

    This program works fine from the command line. I wrote this using the Python extension approx. 6 months ago on another mac. I recently picked up this program again and it shows me the import errors as shown in the attached screenshot. I know that it is pylint related. I am also attaching my user settings and workspace settings screenshots

    Expected behavior

    It should not show errors for import

    Steps to reproduce:

    See the screenshorts

    Logs

    Output for Python in the Output panel (ViewOutput, change the drop-down the upper-right of the Output panel to Python)

    6,0,error,E0401:Unable to import ‘vglabs_common’
    7,0,error,E0401:Unable to import ‘vglabs_anis’
    8,0,error,E0401:Unable to import ‘vglabs_brz’
    10,0,error,E0401:Unable to import ‘vglabs_inf’
    11,0,error,E0401:Unable to import ‘vglabs_mrp’
    12,0,error,E0401:Unable to import ‘vglabs_nmr’
    13,0,error,E0401:Unable to import ‘vglabs_op’
    14,0,error,E0401:Unable to import ‘vglabs_re’
    15,0,error,E0401:Unable to import ‘vglabs_ssk’
    16,0,error,E0401:Unable to import ‘vglabs_txc’
    17,0,error,E0401:Unable to import ‘vglabs_xrd’
    ##########Linting Output — pylint##########
    No config file found, using default configuration
    ************* Module vglabs_uploader
    6,0,error,E0401:Unable to import ‘vglabs_common’
    7,0,error,E0401:Unable to import ‘vglabs_anis’
    8,0,error,E0401:Unable to import ‘vglabs_brz’
    10,0,error,E0401:Unable to import ‘vglabs_inf’
    11,0,error,E0401:Unable to import ‘vglabs_mrp’
    12,0,error,E0401:Unable to import ‘vglabs_nmr’
    13,0,error,E0401:Unable to import ‘vglabs_op’
    14,0,error,E0401:Unable to import ‘vglabs_re’
    15,0,error,E0401:Unable to import ‘vglabs_ssk’
    16,0,error,E0401:Unable to import ‘vglabs_txc’
    17,0,error,E0401:Unable to import ‘vglabs_xrd’
    59,0,refactor,R0912:Too many branches (15/12)
    107,0,refactor,R0912:Too many branches (15/12)
    5,0,warning,W0611:Unused import psycopg2
    XXX

    
    Output from `Console` under the `Developer Tools` panel (toggle Developer Tools on under `Help`)
    
    

    XXX

  • Ошибка unable to find vl gothic font
  • Ошибка unable to find the ubisoft game launcher please reinstall assassins код ошибки 1
  • Ошибка unable to find module info file
  • Ошибка unable to find compatible videocard
  • Ошибка unable to find an ini file please reinstall fallout 4