Reportmissingimports python как исправить

I keep getting error "X" could not be resolved Pylance(reportMissingImports) [ln 1, Col8] I AM in fact a beginner, the basic youtube "fixes" are NOT working View Command Pallet...

I keep getting error «X» could not be resolved Pylance(reportMissingImports) [ln 1, Col8]

I AM in fact a beginner, the basic youtube «fixes» are NOT working

  • View Command Pallet … NOT working
  • Terminal pip install …. NOT working
    I am running the Zip install on my work computer and im guessing it has something to do with a directory. but i cant seem to figure it out. the bottom left corner shows the python version which is ( Pyhton 3.110a7 64-bit(windows store)

asked Apr 19, 2022 at 1:29

Prabhat Mcdonnough's user avatar

2

Pylance requires you to set the Python PATH:

If you’re in Mac/linux, make use of :

which python3

And in windows:

where python

So that the path in which you’re python is installed is returned

Copy that path.

Go to your vscode and open the settings.json file (CTRL + SHIFT + P, and type «settings.json» at search bar)

Add the following key to the json file

"python.defaultInterpreterPath": "/Users/YOURUSERNAME/opt/anaconda3/bin/python3"

This was just an example, the PATH could be something more like
«C:/users/YOURUSERNAME/anaconda3/bin/python3» in case you’re using windows.

The following documentation from python for vscode provides more information about how to configure Python for Visual Studio Code:
https://code.visualstudio.com/docs/python/settings-reference

alramdein's user avatar

alramdein

7602 gold badges9 silver badges25 bronze badges

answered Apr 19, 2022 at 1:57

Vitor Pereira Barbosa's user avatar

2

There’s a very comprehensive discussion on settings in VS Code here: https://stackoverflow.com/a/63211678/5709144.

In summary and with regard to this specific case, it’s better to change settings by going to (on a Mac) Code > Preferences > Settings.

Enter python.defaultInterpreterPath in the search box at the top of screen. The current path is shown in an editable text box.

Enter any path you like here — foobar, mother, whatever you like. It doesn’t matter as, if the path isn’t recognised by VS Code, VS Code lists those that are. The only reason you enter the path is to get the list of potential paths. Click on one of these accepted paths and you’re all set up.

answered Aug 16, 2022 at 21:09

amunnelly's user avatar

amunnellyamunnelly

1,06413 silver badges21 bronze badges

As asked, your question doesn’t specify whether or not your imported module is correctly installed. If it isn’t, then this answer will not apply. However, if your code works as expected and you’re getting a false warning, then you can ignore the warning by doing the following.

Create the file .vscode/settings.json in your current directory and then add the following:

"python.analysis.diagnosticsSeverityOverrides": {
    "reportMissingImports": "none",
}

Be warned however that this will ignore all missing import warnings, not just the one you’re trying to get rid of. Therefore, if you have any imports that are legitimately missing, the warning will not be there.

answered Oct 12, 2022 at 20:03

piccoloser's user avatar

piccoloserpiccoloser

1331 silver badge7 bronze badges

Also, on some occasions, you might have configured your environment by adding custom paths that Pylance can not detect.

In that case, you can use the python.analysis.extraPaths parameter to add more paths to your project, such as :

"python.analysis.extraPaths": ["app", "another/path/etc"]

(Source: https://dev.to/climentea/how-to-solve-pylance-missing-imports-in-vscode-359b)

answered Oct 12, 2022 at 6:45

Cyril N.'s user avatar

Cyril N.Cyril N.

38.2k35 gold badges133 silver badges236 bronze badges

If you are using the VS, Please go to the settings .. search for Advance path and then ADD it (/.source) it should solve the problem.

Hope you have installed the Pylance in your system correctly.

answered Oct 1, 2022 at 9:53

Akash Ray's user avatar

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

RussellJQA opened this issue

Jul 4, 2020

· 16 comments

Comments

@RussellJQA

Environment data

  • Language Server version: 2020.6.1
  • OS and version: Windows 8.1 Pro and Windows 10 2004 Home
  • Python version (& distribution if applicable, e.g. Anaconda): 3.8.3 64-bit, no virtual environment

Expected behaviour

If files helloworld.py and hello_world.py have identical contents, then Pylance should treat «import helloworld» and «import hello_world» identically as well.

Actual behaviour

Pylance reports no error for «import helloworld», but (under the conditions explained below) for «import hello_world» it reports:
Import «hello world» could not be resolved
Pylance (reportMissingImports) [1,8]

In C:Projectsimporttests, I have a helloworld subfolder. The subfolder contains 3 files: helloworld.py, hello_world.py, and callhelloworld.py. callhelloworld imports the other 2 files:
• When I open VSCode (using Windows Explorer’s context menu) from within C:Projectsimporttestshelloworld, then I do NOT see this problem.
• When I instead open VSCode from within C:Projectsimporttests, then I DO see this problem

I originally saw this problem while doing (as a student) exercises from the Python track of exercism.io.
• The provided unittest files which import a filename containing an underscore («_») exhibit this problem. [See https://github.com/exercism/python/blob/master/exercises/hello-world/hello_world_test.py.]
• Those importing only filenames without underscores don’t exhibit this problem. [See https://github.com/exercism/python/blob/master/exercises/raindrops/raindrops_test.py.]

I did not see this problem with my previous (to Pylance) language server.

Logs

[FG] parsing: c:Projectsimporttesthelloworldcallhelloworld.py (22ms)
[FG] parsing: c:Usersrljohnson.vscodeextensionsms-python.vscode-pylance-2020.6.1servertypeshed-fallbackstdlib2and3builtins.pyi (419ms)
[FG] binding: c:Usersrljohnson.vscodeextensionsms-python.vscode-pylance-2020.6.1servertypeshed-fallbackstdlib2and3builtins.pyi (229ms)
[FG] binding: c:Projectsimporttesthelloworldcallhelloworld.py (1ms)
[BG] analyzing: c:Projectsimporttesthelloworldcallhelloworld.py ...
[BG]   parsing: c:Projectsimporttesthelloworldcallhelloworld.py (74ms)
[BG]   parsing: c:Usersrljohnson.vscodeextensionsms-python.vscode-pylance-2020.6.1servertypeshed-fallbackstdlib2and3builtins.pyi (457ms)
[BG]   binding: c:Usersrljohnson.vscodeextensionsms-python.vscode-pylance-2020.6.1servertypeshed-fallbackstdlib2and3builtins.pyi (202ms)
[BG]   binding: c:Projectsimporttesthelloworldcallhelloworld.py (1ms)
[BG]   checking: c:Projectsimporttesthelloworldcallhelloworld.py (1ms)
[BG] analyzing: c:Projectsimporttesthelloworldcallhelloworld.py (735ms)

Code Snippet / Additional information

# File hello_world.py:
def hello():
	return "Hello, World!"

# File helloworld.py:
def hello():
	return "Hello, World!"

# File callhelloworld.py:	
import hello_world
import helloworld

hello_world.hello()
helloworld.hello()

helloworld.zip

@erictraut

Pylance doesn’t know which search paths will be used at the time you execute your Python code. You need to tell it. By default, Pylance will assume that the search paths will include the root of the workspace you open. It also automatically adds a subdirectory called «src» if it’s present, since it’s common practice to place your code within a subdirectory of that name. Any other subdirectories that should be included in the search path must be specified using the «python.analysis.extraPaths» setting.

In your example above, you would want to add the following:

"python.analysis.extraPaths": ["helloworld"]

The reason that «helloworld» is being resolved and «hello_world» is not is that the search paths that you have specified include a directory called «helloworld», and it is being treated as a namespace package.

While investigating your bug report, I did find one bug in Pylance, which I have now fixed. When it detected a namespace package, it was not continuing the scan to find a regular module. The Python spec indicates that regular modules or submodules should be preferred over namespace packages. A fix for this bug will be in the next version of Pylance.

RussellJQA, ottokruse, daeh, MatheusBrochi, elisaliv, phtechwohletz, AmitPhulera, Ajudev, petervenables, birmjin10000, and 11 more reacted with thumbs up emoji

@RussellJQA

Thanks for your helpful explanation. Since CPython itself, my Python linters (prospector within VS Code and pylint outside of it), and my previous VS Code Python language server («Jedi») didn’t complain about this, I hadn’t realized importing like this was a problem. But now I understand why it is.

I tried renaming my helloworld folder to mysubfolder, and verified that Pylance complained about both imports. Then I temporarily changed back to «Jedi», and it didn’t complain about either of them. But then I temporarily changed my Python language server to «Microsoft», and it complained about both imports, too. So, it seems that Pylance is consistent with how the «Microsoft» Python language server does things.

So far, I’ve downloaded 13 of Exercism.io’s 117 Python exercises, and 7 of them have this problem. That’s because for some reason they used dashes in their folder names, but underscores in their filenames. So, folder hello-world contains file hello_world.py, which Pylance complain about importing. To avoid encountering this with future Exercism.io Python exercise files, though, I found there’a an easy enough workaround. As explained in Pylance’s README I just created a workspace settings.json to override this warning for my Exercism project:

{
    "python.analysis.diagnosticSeverityOverrides": {
        "reportMissingImports": "none"
    }
}

Pylance will still warn me about this with my own projects. But that will help encourage me to be more specific about my imports (or at least to name my folders and filenames more carefully).

Thanks again.

Pylance complains about both imports, but Jedi does not complain about either

smurugu, maxmin93, luantorrex, zero-src, juancolchete, ashishpathak30, haris18896, Llanthu, ccbien, mohamedt-ea, and 3 more reacted with thumbs up emoji
boxy-robot, mohamedt-ea, and CantCode023 reacted with hooray emoji
Ali-Aref and CantCode023 reacted with heart emoji

@elisayys

i meet this problems too , and i had uninstell pylance !

mmdalix, marc-hern, geo-tungnt, Sanchit-20, Singh-Sonal, gitfourteen, usalko, and tocjhiestand reacted with thumbs up emoji
Lyte-e, fhh2626, Kurt-Shiwz, NikolasMelui, espetro, marc-hern, SponzaMasoma20, aboueleyes, and VMNg reacted with laugh emoji
Ed1123, AllanDaemon, Qwerty-1331, xarmandop, waikyaw-dtgo, groussea, johnsliao, Lyte-e, RylandCai, dvdblk, and 2 more reacted with eyes emoji

@jakebailey

@RussellJQA

@elisayys

i meet this problems too , and i had uninstell pylance !

If this is still a problem for you, you can workaround it by simply adding:

"python.analysis.diagnosticSeverityOverrides": {
    "reportMissingImports": "none"
}

to your settings.json file.

If, like me, you only want to do that for a certain project, then you can add those lines to a project-level settings.json file (instead of to the main VSCode-wide settings.json file). For a project which doesn’t yet have its own project-level settings.json file, you just create a new settings.json file at the root level of your project, containing simply:

{
    "python.analysis.diagnosticSeverityOverrides": {
        "reportMissingImports": "none"
    }
}

For example, to do this only for a project stored at C:Usersuser1Exercismpython, just create a new C:Usersuser1Exercismpythonsettings.json file consisting only of the lines above.

@Ed1123

Pylance doesn’t know which search paths will be used at the time you execute your Python code. You need to tell it. By default, Pylance will assume that the search paths will include the root of the workspace you open. It also automatically adds a subdirectory called «src» if it’s present, since it’s common practice to place your code within a subdirectory of that name. Any other subdirectories that should be included in the search path must be specified using the «python.analysis.extraPaths» setting.

I think Pylance should include the path of the current open python file alongside the workspace root. It is the common behavior I was expecting when switching to it. I need to do imports on different test on different folders. Jedi is still doing the trick for me.

ewerybody, codenotworking, Zadigo, harshlavingia, duyipai, groussea, DavidAG2000, pascal456, ponugoti, mh70cz, and 2 more reacted with thumbs up emoji
ponugoti reacted with rocket emoji

@eliasyishak

Pylance doesn’t know which search paths will be used at the time you execute your Python code. You need to tell it. By default, Pylance will assume that the search paths will include the root of the workspace you open. It also automatically adds a subdirectory called «src» if it’s present, since it’s common practice to place your code within a subdirectory of that name. Any other subdirectories that should be included in the search path must be specified using the «python.analysis.extraPaths» setting.

I think Pylance should include the path of the current open python file alongside the workspace root. It is the common behavior I was expecting when switching to it. I need to do imports on different test on different folders. Jedi is still doing the trick for me.

^^ I agree, it’s not what most people are used to — I understand adding the path to directory in your file works but it becomes a problem when you work with multiple projects within the workspace

@jakebailey

This issue was about a specific bug in the import code affecting modules that contained the character _. I have made #253 to better capture the «script imports» problem as this feedback shouldn’t be discussed on old closed issues.

@jacob-02

"python.analysis.diagnosticSeverityOverrides": {
        "reportMissingImports": "none"
    }

This code does help remove the error, but it doesn’t provide the autocomplete features. I am using OpenCV and on importing cv2, the same error shows up. Any clues on how to fix it?

Screenshot from 2021-07-06 19-54-37

@jakebailey

Hiding the warning doesn’t fix the issue that we didn’t resolve the import, it just hides the warning. We can’t analyze modules we can’t resolve.

In any case, your issue is definitely not related to this one, which has been closed for some time. We have a few open issues related to cv2; they may be related to what you are seeing.

@jacob-02

I got it fixed tho. But thanks!

@roboserg

I got it fixed tho. But thanks!

How?

@jacob-02

@hdouhua

I used this setting:

{
    "python.pythonPath": "/path_to_python/python3",
    "python.autoComplete.extraPaths": [
        "/path_to_pip/site-packages"
    ],
    "python.analysis.extraPaths": [
        "/path_to_pip/site-packages"
    ],
}

@goktugerol-dev

I use Python Anaconda most of the time and my linux have it’s default Python 3.xxx just like most Linux distros. I had this error when I launched a project that I was working on with Anaconda, I just changed the default Python with Conda distro from the IDE and the error gone. I hope this helps.

@AlfyThomas

name ‘admin’ is not defined

wasd_qwerty

0 / 0 / 0

Регистрация: 26.10.2021

Сообщений: 5

1

12.03.2022, 19:31. Показов 5148. Ответов 3

Метки нет (Все метки)


Хочу использовать библиотеку pyfiglet
С помощью pip install установил её
В консоли проверил работоспособность библиотеки, все работает, а значит импортировалось нормально вроде
Но вот в Visual Studio Code при использовании строки

Python
1
from pyfiglet import Figlet

возникает ошибка Import «pyfiglet» could not be resolved Pylance (reportMissingImports)
Помню раньше была такая же проблема с requests, но проблему решил, а как решил не помню и найти не могу
Помогите пожалуйста

Проблема при импорте библиотек в Visual Studio Code

Проблема при импорте библиотек в Visual Studio Code

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



0 / 0 / 0

Регистрация: 26.10.2021

Сообщений: 5

12.03.2022, 19:38

 [ТС]

2

Уже не нужна помощь все таки нашёл как исправить
Файл — Настройки — Параметры — Расширения — Pylance и добавил Extra Paths до папки с библиотеками
Извините, за беспокойство



0



0 / 0 / 0

Регистрация: 26.10.2021

Сообщений: 5

12.03.2022, 19:53

 [ТС]

3

По всей видимости проблема не решилась, так как теперь вместо Import «pyfiglet» could not be resolved Pylance (reportMissingImports) пишет что нет модуля с таким именем при запуске кода, хотя пока писал сам код VS Code не жаловался(

Проблема при импорте библиотек в Visual Studio Code

Снова помогите



0



Нарушитель

Эксперт PythonЭксперт Java

14042 / 8230 / 2485

Регистрация: 21.10.2017

Сообщений: 19,708

20.03.2022, 15:10

4



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

20.03.2022, 15:10

4

Pylance, by default, includes the root path of your workspace. If you want to include other subdirectories as import resolution paths, you can add them using the python.analysis.extraPaths setting for the workspace.

  • In VS Code press <ctrl> + <,> to open Settings.
  • Type in python.analysis.extraPaths
  • Select «Add Item»
  • Type in the path to your library /home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts/
1) Solution

Pylance, by default, includes the root path of your workspace. If you want to include other subdirectories as import resolution paths, you can add them using the python.analysis.extraPaths setting for the workspace.

  • In VS Code press <ctrl> + <,> to open Settings.
  • Type in python.analysis.extraPaths
  • Select «Add Item»
  • Type in the path to your library /home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts/
2) Solution

Two methods below:

  1. In VS code you can edit the setting.json file. If you add "python.analysis.useImportHeuristic": true the linting error will be removed.

  2. The alternative is to add # type: ignore at the end of the import code.

Here is the github link that i got the above resolution from: https://github.com/microsoft/pylance-release/issues/68

It worked for me: python 3.9, VScode, windows10

3) Solution

By default python selects the global interpreter as the interpreter for any python project you have. So the module/package resolution is in the global context. For any linter you are using to pick up your installed modules you have to ensure you select the correct interpreter

For instance, if you have ever worked with pycharm it does ask you to select the interpreter and create virtual environment with the selected interpreter. For the same, if you start a project in visual studio code It takes the global interpreter as the default interpreter even if you create a virtual environment See this on the bottom left section for the selected interpreter

enter image description here

So how do you ensure Pylance/Pylint/ reads modules installed in the virtual environment created? You need to check for the selected interpreter at the bottom left and if not activated on the virtual environment click on the selected interpreter and vs-code will prompt you to select a default interpreter for the project. Select your current virtual environment and visual studio pylance will read the modules in the current environment. Hope this works for anyone who’s struggling with the same

enter image description here

enter image description here

4) Solution

I was facing similar issue, even after having packages on my system, VS Code Pylance was not able to resolve imports.

In my case I had 2 different versions of python installed (one using anaconda distribution and other directly from python.org)

Fix: Select right python interpreter in VS code. Pylance will stop complaining :)

enter image description here

5) Solution

Another option is to add an .env file at the root of the vscode project. For example:

.env

PYTHONPATH=src/mydir

You either use a relative path like above, or the full path. The benefit of .env is that it will fix both pylance and pylint in vscode. And it’s easier to commit and share on git than .vscode/settings.json.

6) Solution

Pylance is the default the language server used for python project unless you specify it otherwise. If you get (reportMissingImports) and you are sure the dependency has been successfully installed, it means it’s installed somewhere else than Pylance expected. This usually happens if you are working with virtual environements.

Pylance by default selects the system python interpreter for any python project, in this case you need to tell Pylance where to find the virtualenv python interpreter by defining this your vscode settings. Under .vscode/settings.json add the following:

{
    "python.defaultInterpreterPath": "~/.pyenv/versions/3.10.2/envs/<my-virtual-env-name>/bin/python",
    "python.linting.ignorePatterns": [
        "**/site-packages/**/*.py"
    ],
}

Now Pylance will know exactly where to look for the installed dependency. In my case I’m using pyenv but it may be any other path depending on what virtualenv tool you use. If you have other dependencies in other custom location, you can add them by specifying "python.analysis.extraPaths":

{
    "python.defaultInterpreterPath": "~/.pyenv/versions/3.10.2/envs/<my-virtual-env-name>/bin/python",
    "python.linting.ignorePatterns": [
        "**/site-packages/**/*.py"
    ],
    "python.analysis.extraPaths": [
        "my-custom-path-1/python/scripts", 
        "my-custom-path-2/something-else"
    ],
}
7) Solution

If you are using Anaconda environment, a workaround is to add your personal library path to ‘python library path’ via the command conda develop path/to/your/module.

8) Solution

Add this to your settings.json in vscode:

   "python.analysis.extraPaths": ["ml/py"],

it can be a relative path based on the root of your project or an absolute path. You can also have several of them.

9) Solution

In VS studio code

  1. Open your folder
  2. Right Click on the workspace where all the files or folders are
  3. Add folder to workspace
  4. Select the directory on what you inputted in sys.path.insert("DIRECTORY")
10) Solution

I faced similar issue and resolved it by,

  1. Opening the Command Palette (Ctrl+Shift+P).
  2. Search and Select Interpreter.
  3. Browse & Select the virtual environment that you are working with,
  4. Navigate to the scripts folder and select the python application.

and voila all your yellow squiggly lines disappear like fart in thin air. Quote credit: Warden from SSR.

Comments Section

will it resolve if you do import General, what if you add the path to PYTHONPATH before starting VSC. Maybe PyLance only wants relative paths in "python.analysis.extraPaths"

Thanks for your hint. It made me try out additional measures (see EDIT of my initial post above). I still get the same warning message from pylance. Apart from that, an absolute path should always work as far as I’m concerned, but even if this was the issue, now there are all python— and sys-paths set within my project-venv, and still pylance doesn’t recognize it.

then consider filing an issue with PyLance not adhering to PYTONPATH, but how do the virtual environments merge the local and system installed modules, PyLance can handle these

Now, for some reason, it stopped throwing the warnings. I don’t know how it got resolved, but for now I closed the issue posted on the pylance GitHub website: github.com/microsoft/pylance-release/issues/724

Thanks for your reply. Yet, as you can see in my post, I’ve already tried that with no avail. Maybe it has an effect now. As soon as I get to try it out, I’ll let you know.

i get the same linting issue. It appears as though there is still no solution other than to add # type: ignore at the end of the import statement.

Thanks for your contribution. I’ve also followed the git-discussion and saw the "python.analysis.useImportHeuristic": true, I’ll try it out once I get to it. As for the 2nd alternative, this workaround was already mentioned in my initial post and seems to be the last resort, if nothing else works.

comment noted. I confirm that both methods work on the setup that i have, although it seems that you are using Lubuntu 20.04 whereas i tested on windows10. so would be useful to know that it is platform agnostic or otherwise.

Just checked it on Windows 10, in my settings.json the line "python.analysis.useImportHeuristic": true is greyed out. When I hover over it, it states «Unknown Configuration Setting».

@AndreasL. Same happened to me when I got the "Unknown Configuration Setting". Did you find a workaround for this?

Is there a less specific solution? I mean, if I use this solution, I have to add all the paths to all the folders where any test scripts are located.

I use virtualenv for my (Django) project and I had to reference the path for this to work: ~/.virtualenvs/<project directory>/Lib/site-packages/

This is expected as it is a hidden option. github.com/microsoft/pylance-release/issues/…

In addition to this, make sure to select and activate the correct Python environment.

This works perfectly when the «source» folder is named something else than «src».

This works, but some of us are also trying to add other sys.paths outside of the current env, and Pylance will not recognize them, even if they are setup correctly and work when we run the py files. This Example was the only thing that worked for me.

You can add those paths in the ./vscode/settings.json from where vscode reads all configurations from if the settings.json is set

why would a Multi Root Workspace solve the PyLance reportMissingImports problem, where in Explorer do you right click? Add Folder to Workspace is part of the File menu

Related Topics
python-3.x
visual-studio-code
pylance
vscode-settings
python-import

Mentions
Dhia
Felix Orinda
David Dehghan
Edward Funny Hands
Ryan
Wisbucky
Tarun Kumar
Xiaoyue Cao
Adrian Ladia
Lin Felix

References
stackoverflow.com/questions/65252074/import-path-to-own-script-could-not-be-resolved-pylance-reportmissingimports

Это похожая ситуация, с которой я столкнулся несколько месяцев назад, используя pylint до pylance:

Мой python 3.9x — скрипт (с использованием VS Code на Ubuntu 20.04 LTS) начинается со следующего импорта пользовательских «инструментов»:

import sys
sys.path.append(
    '/home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts/'
)

import General.Misc.general_tools as tools

Теперь Pylance заявляет:

Import "General.Misc.general_tools" could not be resolvedPylance (reportMissingImports)

Это происходит даже при том, что во время выполнения программы модуль прекрасно импортируется.

Таким образом, чтобы убедиться, что Pylance понимает, что это существующий путь к модулю, в дополнение к sys.path.append(..) — подходу, я добавил следующее в settings.json — файл:

{
    ...
    // Possible values: "Jedi", "Pylance", "Microsoft", "None".
    "python.languageServer": "Pylance",
    // NOTE on changing from microsoft to pylance language server: python.autoComplete.extraPaths --> python.analysis.extraPaths
    // Docs: https://github.com/microsoft/pylance-release/blob/master/TROUBLESHOOTING.md#unresolved-import-warnings
    "python.analysis.extraPaths": [
        "/home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts"
    ],
    ...
}

Тем не менее, я все еще получаю reportMissingImports-сообщение, хотя оно правильно импортируется.

Обходной путь, который я нашел здесь работает хорошо (добавление # type: ignore к оператору импорта):

import General.Misc.general_tools as tools  # type: ignore

Тем не менее, это всего лишь обходной путь, поэтому я и пытаюсь решить корень этой проблемы. Технически это тот же обходной путь, который я использовал ранее, чтобы избавиться от подобных предупреждающих сообщений от pylint. Вероятно, это что-то присущее VS-Code settings.json — конфигурации, так как использование VS-Code является здесь постоянным фактором.


ИЗМЕНИТЬ дополнительные меры, которые не решили проблему:

Я добавил

export PYTHONPATH="$PYTHONPATH:/home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts"

В мой ~/.bashrc — файл, который теперь позволяет мне импортировать модуль непосредственно в python-оболочку из терминала без предыдущей манипуляции с sys-путем. Однако это относится только к глобальной системной среде Python, но не к какой-либо виртуальной среде. Чтобы изменить там системный путь, я следовал этим инструкциям, в то время как моя конкретная виртуальная среда «scrapy_course» открыта, вот так:

(scrapy_course) andylu@andylu-Lubuntu-PC:~/$ add2virtualenv /home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts

Эта команда применяется для virtualenvwrapper, который управляет виртуальными средами в сочетании с pyenv аккуратно. Теперь я могу запустить свой вышеупомянутый скрипт в текущей среде даже без sys.path.append(...) до импорта модуля, НО pylance по-прежнему не распознает пути правильно и показывает мне то же предупреждение, что и раньше.


ИЗМЕНИТЬ "python.analysis.useImportHeuristic": true:

У меня эта опция постоянно активировалась в моем глобальном settings.json — файле, но я не заметил никакого эффекта. Я буду держать вас в курсе, как только это изменится, или, наконец, на моем пути появится (другое) решение.


EDIT при подавлении/отключении linting-сообщения Pylance «reportMissingImports»:

Я узнал как полностью подавить конкретное сообщение Pylance-linting, если это вас интересует как обходной путь . Особенно в моей текущей ситуации мне нужно использовать pylintв parallel в любом случае, поэтому я вообще не завишу от линтера Pylance.

7 ответов

Я столкнулся с аналогичной проблемой, даже после того, как в моей системе были пакеты, VS Code Pylance не смог разрешить импорт.

В моем случае у меня было установлено 2 разные версии python (одна с использованием дистрибутива anaconda, а другая напрямую с python.org).

Исправлено: выберите правильный интерпретатор Python в коде VS. Пайланс перестанет жаловаться :)

enter image description here


2

Tarun Kumar
31 Окт 2021 в 09:04

Другой вариант — добавить файл .env в корень проекта vscode. Например:

.env

PYTHONPATH=src/mydir

Вы либо используете относительный путь, как указано выше, либо полный путь. Преимущество .env заключается в том, что он исправит как pylance, так и pylint в vscode. Кроме того, легче зафиксировать и поделиться на git, чем на .vscode/settings.json.


1

wisbucky
14 Янв 2022 в 22:22

Pylance — языковой сервер по умолчанию, используемый для проекта Python, если вы не укажете иное. Если вы получаете (reportMissingImports) и уверены, что зависимость была успешно установлена, это означает, что она установлена ​​где-то еще, чем ожидал Pylance. Обычно это происходит, если вы работаете с виртуальными средами.

Pylance по умолчанию выбирает системный интерпретатор python для любого проекта python, в этом случае вам нужно указать Pylance, где найти интерпретатор python virtualenv, указав это в своих настройках vscode. Под .vscode/settings.json добавьте следующее:

{
    "python.defaultInterpreterPath": "~/.pyenv/versions/3.10.2/envs/<my-virtual-env-name>/bin/python",
    "python.linting.ignorePatterns": [
        "**/site-packages/**/*.py"
    ],
}

Теперь Pylance будет точно знать, где искать установленную зависимость. В моем случае я использую pyenv, но это может быть любой другой путь в зависимости от того, какой инструмент virtualenv вы используете. Если у вас есть другие зависимости в другом пользовательском расположении, вы можете добавить их, указав "python.analysis.extraPaths":

{
    "python.defaultInterpreterPath": "~/.pyenv/versions/3.10.2/envs/<my-virtual-env-name>/bin/python",
    "python.linting.ignorePatterns": [
        "**/site-packages/**/*.py"
    ],
    "python.analysis.extraPaths": [
        "my-custom-path-1/python/scripts", 
        "my-custom-path-2/something-else"
    ],
}


1

Dhia
24 Фев 2022 в 12:33

Если вы используете среду Anaconda, обходной путь — добавить путь к вашей личной библиотеке в «путь к библиотеке python» с помощью команды conda develop path/to/your/module.


0

LinFelix
1 Май 2022 в 13:02

Pylance по умолчанию включает корневой путь вашего рабочего пространства. Если вы хотите включить другие подкаталоги в качестве путей разрешения импорта, вы можете добавить их, используя параметр python.analysis.extraPaths для рабочей области.

  • В VS Code нажмите <ctrl> + <,>, чтобы открыть настройки.
  • Введите python.analysis.extraPaths
  • Выберите «Добавить элемент».
  • Введите путь к вашей библиотеке /home/andylu/Dokumente/Allgemeines_material/Sonstiges/Programming/Python/Scripts/


48

Ryan
20 Апр 2021 в 09:29

Два метода ниже:

  1. В коде VS вы можете редактировать файл setting.json. Если вы добавите "python.analysis.useImportHeuristic": true, ошибка анализа будет удалена.

  2. Альтернативой является добавление # type: ignore в конце кода импорта.

Вот ссылка на github, из которой я получил указанное выше разрешение: https://github.com/ Microsoft/pylance-релиз/проблемы/68

У меня сработало: python 3.9, VScode, windows10


28

D.L
15 Апр 2021 в 01:23

По умолчанию python выбирает глобальный интерпретатор в качестве интерпретатора для любого вашего проекта python. Таким образом, разрешение модуля/пакета находится в глобальном контексте. Для любого линтера, который вы используете для получения установленных модулей, вы должны убедиться, что выбрали правильный интерпретатор.

Например, если вы когда-либо работали с pycharm, вам будет предложено выбрать интерпретатор и создать виртуальную среду с выбранным интерпретатором. То же самое, если вы запускаете проект в коде Visual Studio, он принимает глобальный интерпретатор в качестве интерпретатора по умолчанию, даже если вы создаете виртуальную среду. См. Это в левом нижнем разделе для выбранного интерпретатора.

enter image description here

Итак, как вы гарантируете, что Pylance/Pylint/читает модули, установленные в созданной виртуальной среде? Вам нужно проверить выбранный интерпретатор в левом нижнем углу, и если он не активирован в виртуальной среде, щелкните выбранный интерпретатор, и vs-code предложит вам выбрать интерпретатор по умолчанию для проекта. Выберите текущую виртуальную среду, и Visual Studio pylance прочитает модули в текущей среде. Надеюсь, это сработает для тех, кто борется с тем же

enter image description here

enter image description here


6

Felix Orinda
24 Ноя 2021 в 07:56

Понравилась статья? Поделить с друзьями:
  • Reporting this error helps to improve this software this report might include personal information
  • Reporting services http error 503
  • Reported unc error что это
  • Reported unc error что такое victoria
  • Reported unc error как исправить