Команда python выбрать интерпретатор привела к ошибке

Skip to content


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

Assignees

@karthiknadig

Labels

bug

Issue identified by VS Code Team member as probable bug

investigating

We are looking into the cause of the issue

I have been using VSCode for a while and so far everything was good. Yesterday I created a new django project with it’s own virtual environment. However, something happened to VSCode that it cannot find any interpreters. When I click shift+command+P and type >python: select interpreter, it gives me an error. I can still run my code and it works, which is weird but it is very uncomfortable to work like that because the colors are not highlighted in the code.

asked Oct 18, 2021 at 16:29

Begaiym Kudainazarova's user avatar

1

I ran into this problem with my newly installed VSCode on my Win10,and I fixed it by referring to other people’s blog. The solution is somewhat complicated as follows:

First find the location where Microsoft VS Code is installed, then create a test folder in the same level directory, open this folder with VSCode, create a new VSCode window and open the folder where your python files are located, then select python interpreter.

answered Jun 8, 2022 at 10:50

zero's user avatar

zerozero

212 bronze badges

I also faced the same issue and was able to solve it by doing the following:

I tried reverting to an older version of the python extension to see if that would fix the problem and it fixed the problem.

To install older version of python extension on VScode: Go to Extensions(Ctrl+Shift+X) then right click on the python extension, click on Install Another Version and choose an older version.

I hope this helps others who are facing the same issue!

answered Dec 8, 2022 at 14:13

Shaan Bishwas's user avatar

I created file .ipynb and open it with VS Code. I had the same error.

Then I created folder and put this file to folder. After that, I opened folder with VS Code and try command Python: Select interpreter again. And it works. I was able to choose version of interpreter.

I hope this will be useful to you.

answered Mar 21 at 18:32

Le Chat's user avatar

@karthiknadig There is nothing in the Output > Python panel if I am looking in the correct location. I assume you mean the Output that can be reached by View -> Output. I also don’t see anything in View -> Problems (It simply says «No problems have been detected in the workspace»). In the Help -> Toggle Developer tools I do see some errors and warnings. Interestingly, I see errors with v2020.10.332292344 (which eventually works) and v2021.2.636928669 (which doesn’t work). In both cases, after opening vscode and it begins to load a python project, I get a warning in the bottom right of the workspace:

IntelliCode Python support requires you to use the Microsoft Python Language Server (preview)

When I click on the button: Enable it and Reload Window, the v2020.10 version loads the python interpreter and the v2020.2 never does.

Looking at the error log in the Developer Tools in v2020.2 (after enabling the Microsoft Python Language Server) I see the following errors:

IntelliCode Python support requires you to use the Microsoft Python Language Server (preview). onDidChangeNotification @ notificationsAlerts.ts:40

Cannot activate extension 'Python' because it depends on extension 'ms-toolsai.jupyter', which failed to activate. _logMessageInConsole @ abstractExtensionService.ts:718

Activating extension 'ms-toolsai.jupyter' failed: Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again.. _logMessageInConsole @ abstractExtensionService.ts:718

[Extension Host] (node:81920) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. v @ console.ts:137

In addition to the errors there are 5 warnings 4 of which seem to be related to the same issue

[Extension Host] stack trace: Error: Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again. at w.reject (file:///Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js:2013:16717) at file:///Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js:2013:20787 at async w.doWriteConfiguration (file:///Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js:2013:13896) v @ console.ts:137

So I am wondering why the Extension Host is not able to write to the user settings. Maybe that is the root cause, which produces the errors?

Thoughts? Next steps?

I had the exact same issues above, «Command ‘Python: Select Interpreter’ resulted in an error (command ‘python.setInterpreter’ not found)»

RHEL 7.9
vs-code: 1.52.1(Downgraded from 1.54.3 due to incompatible changes in library dependencies)
python: 3.6.8

Initially, when I tried to run my python files, I would get an error that jupyter notebook could not be loaded. When I finally went to set the interpreter using Shift-ctl-P , I got "Command 'Python: Select Interpreter' resulted in an error (command 'python.setInterpreter' not found)"

Solved it by deleting .vscode in my home directory. I’m guessing this would be %USERPROFILE%.vscode in windows. Relaunching vscode recreated the .vscode directory and then it prompted me to download all the extensions I needed. Not sure if it helps, but I think this may fix most of the problems above.

I have been using VSCode for a while and so far everything was good. Yesterday I created a new django project with it’s own virtual environment. However, something happened to VSCode that it cannot find any interpreters. When I click shift+command+P and type >python: select interpreter, it gives me an error. I can still run my code and it works, which is weird but it is very uncomfortable to work like that because the colors are not highlighted in the code.

asked Oct 18, 2021 at 16:29

Begaiym Kudainazarova's user avatar

1

I ran into this problem with my newly installed VSCode on my Win10,and I fixed it by referring to other people’s blog. The solution is somewhat complicated as follows:

First find the location where Microsoft VS Code is installed, then create a test folder in the same level directory, open this folder with VSCode, create a new VSCode window and open the folder where your python files are located, then select python interpreter.

answered Jun 8, 2022 at 10:50

zero's user avatar

zerozero

212 bronze badges

I also faced the same issue and was able to solve it by doing the following:

I tried reverting to an older version of the python extension to see if that would fix the problem and it fixed the problem.

To install older version of python extension on VScode: Go to Extensions(Ctrl+Shift+X) then right click on the python extension, click on Install Another Version and choose an older version.

I hope this helps others who are facing the same issue!

answered Dec 8, 2022 at 14:13

Shaan Bishwas's user avatar

I created file .ipynb and open it with VS Code. I had the same error.

Then I created folder and put this file to folder. After that, I opened folder with VS Code and try command Python: Select interpreter again. And it works. I was able to choose version of interpreter.

I hope this will be useful to you.

answered Mar 21 at 18:32

Le Chat's user avatar

@karthiknadig There is nothing in the Output > Python panel if I am looking in the correct location. I assume you mean the Output that can be reached by View -> Output. I also don’t see anything in View -> Problems (It simply says «No problems have been detected in the workspace»). In the Help -> Toggle Developer tools I do see some errors and warnings. Interestingly, I see errors with v2020.10.332292344 (which eventually works) and v2021.2.636928669 (which doesn’t work). In both cases, after opening vscode and it begins to load a python project, I get a warning in the bottom right of the workspace:

IntelliCode Python support requires you to use the Microsoft Python Language Server (preview)

When I click on the button: Enable it and Reload Window, the v2020.10 version loads the python interpreter and the v2020.2 never does.

Looking at the error log in the Developer Tools in v2020.2 (after enabling the Microsoft Python Language Server) I see the following errors:

IntelliCode Python support requires you to use the Microsoft Python Language Server (preview). onDidChangeNotification @ notificationsAlerts.ts:40

Cannot activate extension 'Python' because it depends on extension 'ms-toolsai.jupyter', which failed to activate. _logMessageInConsole @ abstractExtensionService.ts:718

Activating extension 'ms-toolsai.jupyter' failed: Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again.. _logMessageInConsole @ abstractExtensionService.ts:718

[Extension Host] (node:81920) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead. v @ console.ts:137

In addition to the errors there are 5 warnings 4 of which seem to be related to the same issue

[Extension Host] stack trace: Error: Unable to write into user settings. Please open the user settings to correct errors/warnings in it and try again. at w.reject (file:///Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js:2013:16717) at file:///Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js:2013:20787 at async w.doWriteConfiguration (file:///Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js:2013:13896) v @ console.ts:137

So I am wondering why the Extension Host is not able to write to the user settings. Maybe that is the root cause, which produces the errors?

Thoughts? Next steps?

Go to vscode

r/vscode

A subreddit for working with Microsoft’s Visual Studio Code




Online




ORIGINAL

what is «command ‘python.setInterpreter’ not found» error(i use python)?

I tried the following

reinstall vs code
re-install python extension
re-install python

how to repair this?

Archived post. New comments cannot be posted and votes cannot be cast.

Oct-24-2018, 09:07 AM
(This post was last modified: Oct-24-2018, 09:07 AM by Larz60+.)

I’ve been fighting this for a week (or more) now, without success.
I am running a virtual environment, and the terminal shows proper python, etc.
however when I try to run by choosing ‘Run python file in terminal’ The virtual environment interpreter is not being used, I know this as it is saying a package isn’t installed, but it is (in venv).
If I try to change interpreter from command palette I get ‘cannot read property map of undefined’.

looking on the VSCode site, others are having the same problem, but none of the suggested solutions work.
I have deleted all extensions except for python to no avail.

This is really slowing me down, and I’m at a loss as to a remedy.
I’m thinking there’s probably something that needs to be modified in settings, but don’t know what that might be.

Any ideas?

Snippsat,
In your VSCode tutorial, you advise setting:
«python»: «$pythonPath $fullFileName»,
in code-runner.executorMap json

Now I have done that, but do I have to manually set that path in my environment, or is this something that VSCode will automatically set to my virtual environment?
I ask because the virtual environment appears not to be set.

Posts: 7,958

Threads: 150

Joined: Sep 2016

Reputation:
581

I am not using code-runner plugin. I select the python interpreter by Cntr+Shift+P and selecting the interpreter for the virtual environment I have. Then it works fine when use Run python file in terminal
No need to activate the environment in the terminal if you are just going to run the file. Of course if you also plan to write commands (e.g. install something via pip in the environment) then it’s another story

Posts: 11,673

Threads: 451

Joined: Sep 2016

Reputation:
448

Quote:I select the python interpreter by Cntr+Shift+P and selecting the interpreter for the virtual environment I have

This worked for me until I updated. Now when I use Ctrl+Shift+P, I see ‘Python: Select Interpreter’, when I click on that, I get the error ‘Cannot read property of undefined’. So cannot set up virtual environment.
That’s why I ask about «python»: «$pythonPath $fullFileName», as this looks lake a possibility (or grasp for the ring). So now to use the virtual environment, since I can’t use ‘Run python file in terminal’, I manually switch to the terminal (which I have activated in the virtual environment) and run python from bash. Pain in the butt as I so liked the shortcut, but it works.

Posts: 6,730

Threads: 120

Joined: Sep 2016

Reputation:
493

Oct-24-2018, 05:18 PM
(This post was last modified: Oct-24-2018, 05:19 PM by snippsat.)

(Oct-24-2018, 03:42 PM)Larz60+ Wrote: Now when I use Ctrl+Shift+P, I see ‘Python: Select Interpreter’, when I click on that, I get the error ‘Cannot read property of undefined’

Then you have a error somewhere.
Look at Select an environment
Look your setting.json.

Search for error or Report it.
Clean install

Posts: 11,673

Threads: 451

Joined: Sep 2016

Reputation:
448

Quote:Look at Select an environment

Have done this,

Quote:After using Python: Select Interpreter

point is I cannot use Python: Select Interpreter I get the error ‘Cannot read property of undefined’

I have completely removed code several times, including deleting the .vscode directory completely.
Have followed you instructions on VSCode from start completely (which has always worked before.
Still get same results.

There are other odd things happening with openSuse (which is now somewhat suspect) such as inability to install pyenv 3.7.0. I am ready to try another distro, but reluctant because of the amount of setup pains required.
I am going to attempt one more complete reload of VSCode.

Quote:Search for error or Report it.

As stated earlier, this error has already been reported (by others), but no clear resolution to date.

Posts: 11,673

Threads: 451

Joined: Sep 2016

Reputation:
448

Oct-27-2018, 09:31 AM
(This post was last modified: Nov-07-2018, 04:27 PM by Larz60+.)

I re-installed VSCode one more time and finally everything works.
There are a few things that I did differently, one of these was the answer, but I can’t say which, I’m just glad that all is working now:

1. I restored code-runner.executorMap to default values, then changes python entry to:
«python»: «$pythonPath $fullFileName»

2. before reloading code, I deleted anything in /tmp related to VSCode.
I am suspecting that this was the part that needed to be done.

3. This is not new as I have been doing it all along, so don’t suspect it.
Delete entire .vscode directory in /home/user

I will post this on the VSCode github page as well.

Posts: 11,673

Threads: 451

Joined: Sep 2016

Reputation:
448

New information:
The above is still valid for re-installation, and I have been running without issue until yesterday, when the original:

Quote:however when I try to run by choosing ‘Run python file in terminal’ The virtual environment interpreter is not being used, I know this as it is saying a package isn’t installed, but it is (in venv)

issue reoccurred. After a lot of digging I found something very subtle was causing my problem:

here’s the sequence of events that caused the issue: when switching from project to project (all with virtual environments), occasionally the compiler used when i chose ‘run python file in terminal’ was not synced with the virtual environment.

  1. Close project 1 (virtual environment) using ‘File —> Close Folder’ to close the the first session (while terminal window still open)
  2. exit VSCode using ‘File —> Exit’.
  3. (sometime later, but during same login session) Open VSCode from GNOME icon.
  4. Select project 2 from welcome menu, using shortcut. Upon opening, the terminal window automatically opens (this was the state I left it upon exit from project 1), but it’s in the proper directory for project 2, however it’s not using the proper virtual environment.
  5. From terminal window, I issue command to start venv: . ./venv/bin/activate. The virtual environment starts, and I see python -V using it and also see pip -V using it, so I feel ebevrthings ok with the terminal.
  6. Using command palette, I select the proper interpreter (or so I think) by selecting (cached)./venv/bin/python.
  7. Everything appears OK.

some time later:

  1. I try compiling using ‘Run python file in terminal’, and get an error message that I am missing a package.
  2. Switch to terminal window and type ‘pip list’. The package is there.

So what went wrong?
It appears that the sequence of events needs to be modified as a work around for what appears to be a subtle bug.

  1. Whenever exiting project by using ‘File —> Close Folder’, first close terminal window.
  2. Open project 2 (from welcome menu shortcut). If you forgot to close terminal window from previous session, close now.
  3. Select the python interpreter for current session.
  4. Now, only after selecting python interpreter, open terminal window, using either View —> Terminal’ or ‘Run python file in terminal’.
  5. all really will bo OK now.

I use same name for all of my virtual environments, and that probably has something to do with the problem. I will update the github VSCode posting I made to reflect the new observations, in the meantime, following the final sequence above will suffice.

Posts: 11,673

Threads: 451

Joined: Sep 2016

Reputation:
448

Still causing issues:

Snippsat wrote:

Quote:Then you have a error somewhere.
Look at Select an environment
Look your setting.json.

  • Cannot use python: select interpreter,
    get error:

    Error:

    expected a string, got undefined
  • I have re-installed VSCode no less than five times.
    removed ./config/Code
    removed ./vscode
    removed any vscode references in tmp
    searched etc for any — did not find entry

    Does not do the trick
    Snippsat, used your VSCode from start — followed each and every step, without success:

  • ~/.config/Code/User/settings.json =
    {
    «php»: «php»,
    «python»: «$pythonPath $fullFileName»,
    «perl»: «perl»,
    «code-runner.runInTerminal»: true,
    «terminal.integrated.scrollback»: 50000
    }
  • $pythonPath $fullFileName — Both environment variables are empty.
  • can manually start my virtual environment, and run python from command line,
    python -V and pip -V show proper versions, which python a,d which pip both show proper location in virtual environment bin location
  • I can run python by using run button, but not by right clicking in code and selecting run code in terminal. The python version being run (from run button) is wrong, not my virtual version.

Manual start virtual environment

Output:

[email protected]:~/.config/Code/User> cd .../CIA-FactBook/ [email protected]:.../CIA-FactBook> . ./CIA-Factbook_venv/bin/activate (CIA-Factbook_venv) [email protected]:.../CIA-FactBook> which python .../CIA-FactBook/CIA-Factbook_venv/bin/python (CIA-Factbook_venv) [email protected]:.../CIA-FactBook> python -V Python 3.6.7 (CIA-Factbook_venv) [email protected]:.../CIA-FactBook> which pip .../CIA-FactBook/CIA-Factbook_venv/bin/pip (CIA-Factbook_venv) [email protected]:.../CIA-FactBook> pip -V pip 18.1 from .../CIA-FactBook/CIA-Factbook_venv/lib/python3.6/site-packages/pip (python 3.6) (CIA-Factbook_venv) [email protected]:.../CIA-FactBook> Python 3.6.7

the thing that bothers me the most is that the environment variables pythonPath and fullFileName are not being populated.
where is that supposed to occur? Is it something that I am supposed to set in my virtual environment? or point to something in .pyenv?

Posts: 11,673

Threads: 451

Joined: Sep 2016

Reputation:
448

Ok,
I’m back up and running again, at least for now.
Totally removed VSCode
… and totally removed pyenv.
found an Opensuse install for pyenv here: https://software.opensuse.org/download.h…kage=pyenv
I installed that. It is not as up to date as snippsat’s method, but it’s a version set up for OpenSuse.
Then reinstalled VSCode (which I think had nothing to do with the cause of my issues)
For now all is working well.

Я впервые устанавливаю Python 3.7.2 и использую расширение Python VS Code.

Когда я бегу python -V я получаю Python 2.7.10 что не правильно!

Когда я выбираю интерпретатор usr/local/bin/python3 в VS Code, я получаю эту ошибку при запуске скрипта:

bash: /Users/erik/Work/Python/usr/local/bin/python3: No such file or directory

Но когда я смотрю usr/local/bin , я вижу, что там есть Python3. Я не уверен, почему VS Code вставляет рабочий каталог перед usr/local/bin ?

Моя первая мысль заключалась в том, что Python3 должен быть в переменной PATH, поэтому я запустил включенную команду Update Shell Profile , которая дает следующую обратную связь:

Теперь, после перезагрузки VS Code, я получаю новую опцию выбора интерпретатора:

Это отличается от Python в usr/local/bin ? Когда я выбираю его, я получаю эту ошибку:

The script isort is installed in ‘/Users/erik/Library/Python/3.7/bin’ which is not on PATH.

Я также получаю эту боковую ошибку:

You are using pip version 18.1. You should consider upgrading via the ‘pip install —upgrade pip’ command.

Но, следуя этим инструкциям, я получаю еще одну ошибку:

В целом, этот процесс и официальная документация кажутся менее удобными для пользователя? По-видимому, мне нужно глубоко покопаться в системных файлах моего Mac в терминале, прежде чем даже написать одну строку кода.

Я пропустил важный шаг здесь?

Как вы установили Python (из Python.org? Вы собрали его из исходного кода? Или используете версию, поставляемую с вашей ОС)? Вы пытались установить путь Python вручную, добавив «python.pythonPath»: «/usr/local/bin/python3» к settings.json ? Если это не сработает, используйте путь, который выводит which python3 , и добавьте его.

Вы можете попробовать открыть свой .bashrc и добавить путь, который, как он говорит, отсутствует. Что касается pip, вы, вероятно, можете заставить его работать с pip2 или pip3.

Как ты запускал питон? Попробуйте щелкнуть правой кнопкой мыши, когда курсор находится над окном редактора, выберите «запустить файл Python в терминале».

@Joey Джоуи, вот откуда внезапно появился путь Library/Frameworks/ в VS Code! (по-видимому, VS Code автоматически нашел этот путь). НО, правильно ли это? Так не должно быть usr/local/bin/ .

@bashrc хм, у меня есть идея, что я добавляю пути по всей своей системе. Есть файл .bash, файл .profile, файл .bash_profile, а теперь файл .bashrc? Что я должен использовать?

Vs code не видит скачанные библиотеки в python

писал раньше код в pycharm , он сразу видел какие библиотеки установлены и сразу помогал дописывать атрибуты и т.д. а vs code не видит скачанные библиотеки как это исправить?

Первое и важное необходимо установить расширение для python. Данное расширение поддерживает заполнение для кода и функцию IntelliSense . IntelliSense — это общий термин для ряда функций, которые и дают подсказки в коде для всех ваших файлов как built-in , так и для сторонних модулей. IntelliSense отображает переменные, методы, объекты классов и документацию в момент ввода. Более подробную информацию можно подчерпнуть на официальной страничке посвещенной данному вопросу.

Поскольку всегда, а правильнее сказать, как правило используются виртуальные пространства, то и модули для будут отличаться от глобальных установок. В этом случае в VSCode предусмотрено переключение на тот интерпретатор, который необходим в данном рабочем процессе.

Приведу пример. При помощи python -m venv env команды я создам виртуальное пространство для проекта, которое будет включать нужную версию python и модули, которые нужны только для данного проекта. Если не конфигурировался проект изначально при запуске VSCode будет цеплять глобальный python и глобальные модули (возможно, в новых версиях это не так). Это можно увидеть в нижнем левом углу интерфейса VSCode

введите сюда описание изображения

При нажатии на данную область появится меню вверху окна с возможностью выбора пространства

введите сюда описание изображения

Где я и могу выбрать нужный мне python 3.8.6 64-bit (‘env’:venv) . Из данного примера можно увидеть, что я могу использовать разные версии python и соответственно модули, для которых и будет работать IntelliSense .

Pip and Python in Visual Studio Code

I’m not a Python expert, but I used it more often these days and I use Visual Studio Code with Python extension to author my scripts. One of the most annoying problem is receiving a no module named xxx error when you already installed that module with pip.

No module error when running Python code in Visual Studio CodeFigure 1: No module error when running Python code in Visual Studio Code

The problem arise because Visual Studio Code is not using the very same installation of python you are using from your command line / terminal. When you edit Python files in Visual Studio Code you should select interpreter path command to specify which version of Python you want to use, as showed in Figure 2:

Choose Python interpreterFigure 2: Choose Python interpreter

This allows you to choose which Python version you want to use, but clearly, when you press F5 that specific version is used and probably you did not install required module in that specific version.

Since Visual Studio Code can use whichever version of Python in your system, you need to install modules for that specific version used.

Once you realize this, solution is straightforward, just install module with pip using the same version of Python chosen as interpreter (Figure 2) using directly python.exe correct version as shown in Figure 3.

Install modules with right version of pipFigure 3: Install modules with right version of pip

Once you installed modules using the very same version chosen as interpreter in VSCode, you are ready to go. Pressing F5 you can now debug your code without problem.

Debugging in VSCode after installing required modulesFigure 4: Debugging in VSCode after installing required modules

Понравилась статья? Поделить с друзьями:
  • Команда пластика не может быть выполнена ошибка диска
  • Колонка нева транзит коды ошибок
  • Колонка бакси ошибка е01 что делать
  • Командировочный специалист лексическая ошибка
  • Команда dism ошибка 740