Как установить requests python visual studio
I'm attempting to import the module requests into a Python file (using Python 2.7.14).
Visual Studio Code outputted this in the console:
ImportError: No module named requests
Upon digging, I discovered I don't have requests installed, so I fixed that with the following commannd from Terminal:
sudo pip install requests , based on this answer with a bazillion upvotes.
I closed VS Code and restarted it, opened my Python file, ran it and I got the same error. I proceeded to try each of the solutions in hopes one would work. None did.
I recently installed anaconda and I suspect that is the source of my problem, so I uninstalled every instance of Python I could find via brew and also stray installations that were parts of other installations that have accumulated over time on my hard disk based on this answer.
I then reinstalled python from scratch after running brew doctor , brew prune , etc.
I also dug into the code settings within Visual Studio Code to see if perhaps that's where my problem was. One of the suggestions was to override the settings for python in the code-runner.executorMap setting, so I typed which python in Terminal to obtain the path to python and updated VS Code's User Settings to the path which python returned. Now, I'm using this as my code-runner.executorMap for python :
I've verified Python is working by throwing in a couple of simple statements in:
The moment I put import requests at the top of the file, I get this error and nothing below it executes:
[Running] /usr/bin/python "/Users/me/Documents/developerNew/python/tempCodeRunnerFile.py" Traceback (most recent call last): File "/Users/me/Documents/developerNew/python/tempCodeRunnerFile.py", line 1, in import requests ImportError: No module named requests
I have my file named something else, so I think my problem lives in the "tempCodeRunnnerFile.py". I tried removing the override for the codeRunner.executorMap , but that doesn't seem to work either.
I'm out of ideas. If you have one, I welcome your suggestion. Thank you for reading.
The Python developer community has produced thousands of useful packages that you can incorporate into your own projects. Visual Studio provides a UI to manage packages in your Python environments.
View environments
Select the View > Other Windows > Python Environments menu command. The Python Environments window opens as a peer to Solution Explorer and shows the different environments available to you. The list shows both environments that you installed using the Visual Studio installer and environments you installed separately. That includes global, virtual, and conda environments. The environment in bold is the default environment that's used for new projects. For more information about working with environments, see How to create and manage Python environments in Visual Studio environments.
You can also use the Ctrl+K, Ctrl+` keyboard shortcut to open the Python Environments window from the Solution Explorer window. If the shortcut doesn't work and you can't find the Python Environments window in the menu, it's possible that you haven't installed the Python workload. See How to install Python support in Visual Studio on Windows for guidance about how to install Python.
With a Python project open, you can open the Python Environments window from Solution Explorer. Right-click Python Environments and select View All Python Environments.
Now, create a new project with File > New > Project, selecting the Python Application template.
In the code file that appears, paste the following code, which creates a cosine wave like the previous tutorial steps, only this time plotted graphically. You can also use the project you previously created and replace the code.
In the editor window, hover over the numpy and matplotlib import statements. You'll notice that they aren't resolved. To resolve the import statements, install the packages to the default global environment.
When you look at the editor window, notice that when you hover over the numpy and matplotlib import statements that they aren't resolved. The reason is the packages haven't been installed to the default global environment.
For example, select Open interactive window and an Interactive window for that specific environment appears in Visual Studio.
The Packages tab in the Python Environments window lists all packages that are currently installed in the environment.
Install packages using the Python Environments window
From the Python Environments window, select the default environment for new Python projects and choose the Packages tab. You'll then see a list of packages that are currently installed in the environment.
Install matplotlib by entering its name into the search field and then selecting the Run command: pip install matplotlib option. Running the command will install matplotlib , and any packages it depends on (in this case that includes numpy ).
Choose the Packages tab.
Consent to elevation if prompted to do so.
After the package is installed, it appears in the Python Environments window. The X to the right of the package uninstalls it.
Enter matplotlib into the search field to install matplotlib .
Select the Run command: pip install matplotlib option. This option installs matplotlib , and any packages it depends on (in this case, that includes numpy ).
Consent to elevation if prompted to do so.
After the package installs, it appears in the Python Environments window. The X to the right of the package uninstalls it.
A small progress bar might appear underneath the environment to indicate that Visual Studio is building its IntelliSense database for the newly-installed package. The IntelliSense tab also shows more detailed information. Be aware that until that database is complete, IntelliSense features like auto-completion and syntax checking won't be active in the editor for that package.
Visual Studio 2017 version 15.6 and later uses a different and faster method for working with IntelliSense, and displays a message to that effect on the IntelliSense tab.
Run the program
Now that matplotlib is installed, run the program with (F5) or without the debugger (Ctrl+F5) to see the output:
Сообщество разработчиков на Python создало тысячи полезных пакетов, которые вы можете включать в свои проекты. В Visual Studio имеется пользовательский интерфейс для управления пакетами в средах Python.
Просмотр окружений
Выберите команду меню Просмотр > Другие окна > Окружения Python. Откроется окно Окружения Python (как узел обозревателя решений), в котором представлены разные среды, доступные вам. Список содержит как окружения, установленные с помощью установщика Visual Studio, так и окружения, которые вы установили отдельно. В их число входят глобальные, виртуальные среды и среды Conda. Среда, выделенная полужирным шрифтом, — это среда, используемая по умолчанию для новых проектов. Дополнительные сведения о работе со окружениями см. в разделе Создание окружений Python и управление ими в средах Visual Studio.
Используйте сочетания клавиш CTRL +K, CTRL +` , чтобы открыть окно Окружения Python из окна Обозревателя решений. Если сочетание клавиш не работает и окно "Окружения Python" отсутствует в меню, возможно, не установлена рабочая нагрузка Python. Инструкции по установке Python см. в статье Установка поддержки Python в Visual Studio в Windows.
Если открыт проект Python, вы можете открыть окно Окружения Python из Обозревателя решений. Щелкните правой кнопкой мыши Окружения Python и выберите пункт Просмотреть все окружения Python.
Теперь создайте проект, выбрав пункт меню Файл > Создать > Проект, а затем выбрав шаблон Приложение Python.
В появившийся файл кода вставьте приведенный ниже код, который строит косинусоиду, как в предыдущих шагах учебника, но теперь в виде графика. Можно также использовать ранее созданный проект и заменить код.
В окне редактора наведите указатель мыши на инструкции импорта numpy и matplotlib . Вы заметите, что они не разрешены. Чтобы разрешить инструкции импорта, установите пакеты в глобальное окружение по умолчанию.
Если в окне редактора навести указатель мыши на операторы импорта numpy и matplotlib , вы заметите, что они не разрешены. Это связано с тем, что пакеты не были установлены в глобальном окружении по умолчанию.
Например, щелкните ссылку Открыть интерактивное окно, и в Visual Studio откроется интерактивное окно для этого окружения.
На вкладке Пакеты в окне "Окружения Python" указаны все пакеты, установленные в настоящий момент в окружении.
Установка пакетов с помощью окна "Окружения Python"
В окне "Окружения Python" выберите окружение по умолчанию для новых проектов Python и перейдите на вкладку Пакеты. Вы увидите список пакетов, которые в настоящее время установлены в окружении.
Установите пакет matplotlib , введя его имя в поле поиска, а затем выбрав параметр Выполнить команду "pip install matplotlib" . При выполнении этой команды будут установлены пакет matplotlib , а также все пакеты, от которых он зависит (в данном случае — numpy ).
Выберите вкладку Пакеты.
Согласитесь на повышение прав, если появится соответствующий запрос.
Установленный пакет появится в окне Окружения Python. Если щелкнуть знак X справа от пакета, он будет удален.
Введите matplotlib в поле поиска для установки matplotlib .
Выберите вариант Выполнить команду: pip install matplotlib. Будет установлен пакет matplotlib , а также все пакеты, от которых он зависит (в данном случае — numpy ).
Согласитесь на повышение прав, если появится соответствующий запрос.
Установленный пакет появится в окне Окружения Python. Если щелкнуть знак X справа от пакета, он будет удален.
Под названием среды может появиться небольшой индикатор выполнения, который указывает на то, что Visual Studio создает базу данных IntelliSense для нового пакета. На вкладке IntelliSense также приводятся более подробные сведения. Имейте в виду, что, пока база данных не будет готова, функции IntelliSense, такие как автозавершение и проверка синтаксиса, будут неактивны для этого пакета в редакторе.
Запуск программы
После установки matplotlib запустите программу с отладчиком (F5) или без него (CTRL+F5), чтобы увидеть результат.
Чтобы установить поддержку Python для Visual Studio (Инструменты Python для Visual Studio или PTVS), выполните инструкции из раздела, который соответствует вашей версии Visual Studio:
Чтобы быстро проверить поддержку Python после установки, откройте интерактивное окно Python. Для этого нажмите клавиши ALT+I и введите 2+2 . Если вы не увидите результат 4 , проверьте выполненные действия.
Рабочая нагрузка Python содержит полезное расширение Cookiecutter, которое предоставляет графический пользовательский интерфейс для поиска шаблонов, ввода параметров шаблонов и создания проектов и файлов. Дополнительные сведения см. в статье Использование расширения Cookiecutter.
Сейчас Python не поддерживается в Visual Studio для Mac, однако доступен в Mac и Linux посредством Visual Studio Code. См. вопросы и ответы.
Visual Studio 2022
Visual Studio 2019
Visual Studio 2017
Скачайте и запустите последнюю версию Visual Studio Installer. Если вы уже установили Visual Studio, запустите Visual Studio Installer, выберите вариант Изменить (см. раздел Изменение Visual Studio) и перейдите к шагу 2.
Выпуск Community предназначен для индивидуальных разработчиков, использования при аудиторном обучении и в научных исследованиях, а также разработки решений с открытым кодом. Если программу планируется использовать в других целях, установите Visual Studio 2022 Professional или Visual Studio 2022 Enterprise.
Выпуск Community предназначен для индивидуальных разработчиков, использования при аудиторном обучении и в научных исследованиях, а также разработки решений с открытым кодом. Если программу планируется использовать в других целях, установите Visual Studio 2019 Professional или Visual Studio 2019 Enterprise.
Установщик Visual Studio предоставляет список рабочих нагрузок, которые представляют собой группы связанных параметров для конкретных областей разработки. Для Python выберите рабочую нагрузку Разработка на Python.
.
В правой части установщика при необходимости выберите другие параметры. Чтобы принять параметры по умолчанию, пропустите этот шаг.
После установки в установщике предлагаются команды для изменения, запуска, восстановления и удаления Visual Studio. Если доступны обновления для установленных компонентов Visual Studio, кнопка Изменить меняется на Обновить. (Команду Изменить в этом случае можно выбрать в раскрывающемся меню.) Запускать среду Visual Studio и установщик можно также из меню Пуск в Windows. Для этого выполните поиск по запросу "Visual Studio".
Рабочие нагрузки для Python и обработки и анализа данных доступны только в Visual Studio2017 версии 15.2 и выше.
Диагностика
Чтобы устранить проблемы при установке или запуске Python в Visual Studio, попробуйте сделать следующее:
- Определите, возникает ли та же ошибка при использовании Python CLI, то есть при запуске python.exe из командной строки.
- Воспользуйтесь восстановлением Visual Studio.
- Восстановите или переустановите Python через Параметры >Приложения и компоненты в Windows.
Visual Studio 2015
Чтобы запустить установщик Visual Studio, откройте Панель управления > Программы и компоненты, затем выберите Microsoft Visual Studio 2015 и нажмите кнопку Изменить.
В самом установщике выберите действие Изменить.
Выберите Языки программирования > Инструменты Python для Visual Studio и нажмите Далее:
Visual Studio 2013 и более ранние версии
Установите версию Инструментов Python для Visual Studio, соответствующую вашей версии Visual Studio.
- Visual Studio 2013: PTVS 2.2.2 для Visual Studio 2013 В Visual Studio 2013 этот процесс можно запустить через диалоговое окно Файл >Новый проект.
- Visual Studio 2010 и 2012: PTVS 2.1.1 для Visual Studio 2010 и 2012
Selecting and installing Python interpreters (Установка и настройка интерпретаторов Python). Если интерпретатор уже установлен, но Visual Studio не обнаруживает его автоматически, см. руководство по определению существующего окружения вручную.
Расположения установки
По умолчанию поддержка Python устанавливается для всех пользователей на компьютере.
В Visual Studio 2022 рабочая нагрузка Python устанавливается в каталог %ProgramFiles%\Microsoft Visual Studio\\Common7\IDE\Extensions\Microsoft\Python, где — это 2022, а — Community, Professional или Enterprise.
По умолчанию поддержка Python устанавливается для всех пользователей на компьютере.
В Visual Studio 2019 и Visual Studio 2017 рабочая нагрузка Python устанавливается в каталог %ProgramFiles(x86)%\Microsoft Visual Studio\\Common7\IDE\Extensions\Microsoft\Python, где — это 2019 или 2017, а — Community, Professional или Enterprise.
В Visual Studio 2015 и более ранних версиях используются такие пути установки:
- 32-разрядная версия.
- Путь: %Program Files(x86)%\Microsoft Visual Studio \Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\
- Расположение пути в реестре: HKEY_LOCAL_MACHINE\Software\Microsoft\PythonTools\\InstallDir
- Путь: %Program Files%\Microsoft Visual Studio \Common7\IDE\Extensions\Microsoft\Python Tools for Visual Studio\
- Расположение пути в реестре: HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\PythonTools\\InstallDir
- принимает одно из этих значений:
- 14.0 for Visual Studio 2015
- 12.0 for Visual Studio 2013
- 11.0 for Visual Studio 2012
- 10.0 for Visual Studio 2010
Пользовательские установки (для версии 1.5 и более ранних)
Инструменты Python для Visual Studio 1.5 и более ранних версий можно установить только для текущего пользователя. Путь установки будет выглядеть так: %LocalAppData%\Microsoft\VisualStudio\\Extensions\Microsoft\Python Tools for Visual Studio\ . Здесь и имеют то же значение, которое описано выше.
I have 1 file, i get as far as line 1 import requests , nothing more yet and I receive the following error ModuleNotFoundError: No module named 'requests' .
- Using Visual Studio Code, installed today with standalone Python x64 3.7.4
- Python Extension installed in VSCODE
- venv created within VSCODE as a subfolder of workspace withint VSCODE terminal and was recognized by VSCODE when created and I am using venv interpreter in VSCODE as indicated on bottom bar
- ran pip install requests within terminal inside VSCODE - completed successfully
- ran pip freeze to confirm requests==2.22.0 is registered
- Verified pylint was installed in venv
I cannot figure out why VSCODE python interpreter will not recognize that requests is installed
5 Answers 5
try get python version in vscode terminal
and check python version vscode IDE used by clicking left buttom corner.
make sure these 2 versions are consistent. if not, select the version of IDE with the same version of your terminal.
Have you checked your user and workspace settings?
Make sure your workspace settings (not your user settings) points to your project's venv path.
I have encountered a similar problem such as yours but was able to solve it by changing the workspace settings python path to point to my venv path as below.
This solved a similar problem for me when the AREPL extension was having this problem, but running the program normally worked. Trying this in the AREPL Python path allowed AREPL to find the module.
Thanks for the responses. I found out my own issue after a few hours.
First off I figured out somewhere that when I was running the terminal in VSCODE it was running against global interpreter. I then tried ./pip freeze and it worked as expected. This told me that the terminal was connected to the wrong interpreter.
For some reason when I would 'run' the file it was executing in the terminal but it wasn't 'activating' the venv. I've closed and reopened VSCODE many times but for some reason when I closed the terminal window and reopened using CTRL+SHIFT+' and I received an error about signed scripts when it tried to activate my venv using the PS1 script. I ran Set-ExecutionPolicy -ExecutionPolicy RemoteSigned inside a normal PowerShell window and then reopened the Terminal window in VSCODE and it successfully activated my venv and I know see my venv name at the beginning of the line of the terminal. I then ran 'pip freeze' to confirm which modules installed inside of venv and then ran again in normal powershell window and it was different.
There is documentation somewhere that says to run Set-ExecutionPolicy -ExecutionPolicy RemoteSigned which I found later, but it would have been nice to know this was a requirement.
Читайте также: