Как изменить интерпретатор в visual studio code
В 2016-м году компания Microsoft представила миру свой новый редактор программного кода. В отличие от старшей сестры — полноценной IDE Visual Studio — VS Code получился куда более компактным и легковесным решением. Он разработан как кроссплатформенное ПО и может быть успешно установлен в системах Windows, Linux и macOS.
Бесплатность Visual Studio Code абсолютно не мешает ему обладать весьма богатым современным функционалом. VS Code имеет встроенный отладчик, позволяет работать с системами контроля версий, обеспечивает интеллектуальную подсветку синтаксиса, а также поддерживает целый ряд популярных языков программирования.
И хоть, за годы своего существования, VSCode зарекомендовал себя, в основном, как продукт для веб-разработки, в 2018 году появилось расширение " Python ", которое дало программистам многочисленные возможности для редактирования, отладки и тестирования кода на нашем любимом языке.
Установка VSCode
Поистине смешные системные требования Visual Studio Code обязательно порадуют владельцев старых машин.
Для полноценной работы редактору требуется всего лишь 1 ГБ оперативной памяти и процессор с частотой от 1.6 ГГц.
Такое сочетание лёгкости и функциональности действительно подкупает, а отсутствие в VS Code каких-либо "лагов" и "фризов" делают разработку ещё более приятным и увлекательным занятием.
Установка редактора никуда не отходит от данной парадигмы и тоже является весьма простым и понятным процессом.
Windows
Сначала нужно скачать с официального сайта установочный файл небольшого размера, а затем установить сам ВиЭс код, следуя подсказкам от мастера установки.
Linux
На сайте программы можно изучить способы инсталляции редактора на разные Linux-дистрибутивы, но здесь рассмотрим процесс установки для самого популярного из них — Ubuntu.
Установить VSCode можно несколькими способами:
Способ №1 : Самый простой способ — воспользоваться менеджером установки "Ubuntu Software".
sudo apt install ./.deb
macOS
Алгоритм установки редактора внутри яблочной операционной системы также не представляет собой ничего сложного:
- Сначала нужно скачать Visual Studio Code с официального сайта.
- Затем открыть список загрузок браузера и найти там VSCode-Darwin-Stable.zip .
- Нажмите на иконку увеличительного стекла, чтобы открыть архив.
- Перетащите Visual Studio Code.app в папку приложений, сделав ее доступной на панели запуска.
- Щёлкните правой кнопкой мыши по значку и выберите команду " Оставить в Dock ".
Настройка под Python
Установка расширения "Python"
Для начала работы с Python, нужно перейти на вкладку Extensions , что находится на панели слева, либо нажать Ctrl + Shift + X . Сделав это, набираем в строке поиска " Python ".
VS Code поддерживает, как вторую, так и третью версию языка, однако python интерпретатор на свою машину вам придётся поставить самостоятельно.
Если вы новичок и только начинаете работу с Python или же не имеете каких-то особых указаний на этот счёт, то лучшим выбором станет именно актуальная третья версия.
Вот краткий список основных возможностей расширения "Python":
- Автодополнение кода.
- Отладка.
- Поддержка сниппетов.
- Написание и проведение тестов.
- Использование менеджера пакетов Conda.
- Возможность создания виртуальных сред.
- Поддержка интерактивных вычисления на Jupyter Notebooks.
Выбор версии интерпретатора Python
После от вас потребуется совершить выбор версии интерпретатора внутри самого редактора (обычно VS code знает, где он расположен). Для этого:
- Откройте командную строку VSCode (Command Palette) комбинацией Ctrl + Shift + P .
- Начинайте печатать " Python: Select Interpreter ";
- После, выберите нужную версию интерпретатора.
Также выбрать версию можно в панели активности в левом нижнем углу:
Если вы хотите использовать pipenv в своем проекте:
- Установите pipenv командой pip install pipenv (или pip3 install pipenv );
- Выполните команду pipenv install ;
- Откройте " Command Palette ", напечатайте " Python: Select Interpreter " и из списка выберите нужную версию интерпретатор.
Работа в VS Code
Запуск редактора
Как и другие современные редакторы и среды разработки, VS Code фиксирует состояние на момент закрытия программы. При следующем запуске, он открывается в том же самом виде, в котором существовал до завершения работы.
Так как VSCode, в первую очередь — редактор, а не полновесная среда разработки, здесь нет особой привязки к проекту. Вы можете сходу создавать, открывать и редактировать нужные вам файлы. Достаточно, после запуска, нажать Open File или New File и можно начинать работу.
Интерфейс
Интерфейс программы разрабатывался в стремлении сделать его как можно более простым и интуитивно понятным. Дизайнеры постарались, как максимизировать пространство для редактора, так и оставить достаточно места для отображения проводника по вашему проекту.
Весь UI VSCode разделился, таким образом, на шесть областей:
- Область редактора — основная область для написания и редактирования вашего кода.
- Боковая панель — здесь содержатся различные представления (например проводник).
- Строка состояния — визуализирует рабочую информацию об открытом в данный момент файле.
- Командная панель — классическая главная панель с вкладками file, edit, go, run и так далее.
- Панель активности — область в крайнем левом углу, где находятся важные вспомогательные вкладки, вроде контроля версий, дебаггера и магазина расширений.
- Мультипанель — панель на которой располагается вывод отладку, информация об ошибках и предупреждениях, а также встроенный в VS Code терминал.
Запуск Python-кода (run)
Выполнить код можно несколькими способами. Самый простой — комбинацией Ctrl + Alt + N .
Также можно вызвать скрипт контекстным меню, выбрав строку " Run Python File in Terminal ".
Или нажав иконку " Run " в правом верхнем углу.
Отладка (debugger)
Возможность полноценной отладки — сильная сторона редактора. Чтобы перейти в режим отладки, нужно установить точку останова и нажать F5 .
Вся информация о текущем состоянии будет выводиться на панель дебаггера.
Слева откроется панель дебаггера с информацией о состоянии переменных (Variables), отслеживаемых переменных (Watch) и стеке вызова (Call stack).
Сверху расположена панель инструментов дебаггера.
Рассмотрим команды (слева направо):
- continue ( F5) — перемещает между breakpoint-ами;
- step over ( F10) — построчное (пошаговое) перемещение;
- step into ( F11) — построчное (пошаговое) перемещение c заходом в каждую вызываемую функцию;
- step out ( Shift + F11) — работает противоположно step into — выходит из вызванной функции, если в данный момент вы находитесь внутри неё. Далее работает как continue .
- restart ( Ctrl + Shift + F5) — начинаем отладку с начала.
- stop ( Shift + F5) — остановка и выход из режима отладки.
С отладкой разобрались 👌.
Тестирование (testing)
С поддержкой тестов у VS Code тоже всё в порядке, однако, по умолчанию тестирование отключено. Для его активации нужна небольшая настройка.
Сначала следует нажать комбинацию клавиш Ctrl + Shift + P и в так называемой палитре команд выбрать Python: Configure Tests .
Для выбора фреймворка для тестов, выполните комбинацию "Ctrl + Shift + P" и наберите "Python: Configure Tests"
Редактор предложит вам определить фреймворк (мы выбрали "pytest") и папку, содержащую тесты (мы выбрали ". Root directory").
Создадим новый файл с тестами ( test_app.py ) и запустим его, кликнув правой кнопкой мыши на этом файле и выбрав пункт " Run Current Test File ".
Чтобы увидеть результаты, необходимо открыть вкладку Output на панели, и в выпадающем меню выбрать пункт PythonTestLog .
Как мы видим, первый тест прошел успешно, а второй провалился.
Для удобства работы с тестами, установим расширение " Python Test Explorer for Visual Studio Code ".
Теперь информацию по тестам можно посмотрев, кликнув на левой панели " иконку с колбой ", предварительно запустив тесты.
Вкладка "test" (иконка с колбой в панели слева) откроет удобный проводник для запуска тестов и просмотра их состояния.
Для начала работы с системами контроля версий обратимся к вкладке Source Control , что находится на панели активности слева (или Ctrl + Shift + G ).
По умолчанию VS Code дружит с Git и GitHub
Поддержку других систем возможно настроить самостоятельно, установив соответствующие расширения.
Чтобы связать проект с github (или gitlab), сперва необходимо скачать на ваш ПК git (если ещё не скачан). VSCode автоматически определит его местоположение, и затем у вас появится возможность синхронизации.
Все основные и необходимые операции для контроля версий будут находиться прямиком внутри редактора: коммитить, пуллить, пушить, создавать бранчи и просматривать изменения вы можете, не выходя из VisualStudioCode.
А для удобного просмотра изменений в git, советую установить расширение " Git Graph ". После его установки, на панели " Source Control " появится новая кнопка, которая отобразит граф состояния (git log).
In this tutorial, you use Python 3 to create the simplest Python "Hello World" application in Visual Studio Code. By using the Python extension, you make VS Code into a great lightweight Python IDE (which you may find a productive alternative to PyCharm).
This tutorial introduces you to VS Code as a Python environment, primarily how to edit, run, and debug code through the following tasks:
- Write, run, and debug a Python "Hello World" Application
- Learn how to install packages by creating Python virtual environments
- Write a simple Python script to plot figures within VS Code
If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.
Prerequisites
To successfully complete this tutorial, you need to first setup your Python development environment. Specifically, this tutorial requires:
- VS Code
- VS Code Python extension
- Python 3
Install Visual Studio Code and the Python Extension
If you have not already done so, install VS Code.
Next, install the Python extension for VS Code from the Visual Studio Marketplace. For additional details on installing extensions, see Extension Marketplace. The Python extension is named Python and it's published by Microsoft.
Install a Python interpreter
Along with the Python extension, you need to install a Python interpreter. Which interpreter you use is dependent on your specific needs, but some guidance is provided below.
Windows
Note: If you don't have admin access, an additional option for installing Python on Windows is to use the Microsoft Store. The Microsoft Store provides installs of Python 3.7, Python 3.8, Python 3.9, and Python 3.10. Be aware that you might have compatibility issues with some packages using this method.
macOS
The system install of Python on macOS is not supported. Instead, an installation through Homebrew is recommended. To install Python using Homebrew on macOS use brew install python3 at the Terminal prompt.
Note On macOS, make sure the location of your VS Code installation is included in your PATH environment variable. See these setup instructions for more information.
Linux
The built-in Python 3 installation on Linux works well, but to install other Python packages you must install pip with get-pip.py.
Other options
Data Science: If your primary purpose for using Python is Data Science, then you might consider a download from Anaconda. Anaconda provides not just a Python interpreter, but many useful libraries and tools for data science.
Windows Subsystem for Linux: If you are working on Windows and want a Linux environment for working with Python, the Windows Subsystem for Linux (WSL) is an option for you. If you choose this option, you'll also want to install the Remote - WSL extension. For more information about using WSL with VS Code, see VS Code Remote Development or try the Working in WSL tutorial, which will walk you through setting up WSL, installing Python, and creating a Hello World application running in WSL.
Verify the Python installation
To verify that you've installed Python successfully on your machine, run one of the following commands (depending on your operating system):
Linux/macOS: open a Terminal Window and type the following command:
Windows: open a command prompt and run the following command:
If the installation was successful, the output window should show the version of Python that you installed.
Note You can use the py -0 command in the VS Code integrated terminal to view the versions of python installed on your machine. The default interpreter is identified by an asterisk (*).
Start VS Code in a project (workspace) folder
Using a command prompt or terminal, create an empty folder called "hello", navigate into it, and open VS Code ( code ) in that folder ( . ) by entering the following commands:
Note: If you're using an Anaconda distribution, be sure to use an Anaconda command prompt.
By starting VS Code in a folder, that folder becomes your "workspace". VS Code stores settings that are specific to that workspace in .vscode/settings.json , which are separate from user settings that are stored globally.
Alternately, you can run VS Code through the operating system UI, then use File > Open Folder to open the project folder.
Select a Python interpreter
Python is an interpreted language, and in order to run Python code and get Python IntelliSense, you must tell VS Code which interpreter to use.
From within VS Code, select a Python 3 interpreter by opening the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), start typing the Python: Select Interpreter command to search, then select the command. You can also use the Select Python Environment option on the Status Bar if available (it may already show a selected interpreter, too):
The command presents a list of available interpreters that VS Code can find automatically, including virtual environments. If you don't see the desired interpreter, see Configuring Python environments.
Note: When using an Anaconda distribution, the correct interpreter should have the suffix ('base':conda) , for example Python 3.7.3 64-bit ('base':conda) .
Selecting an interpreter sets which interpreter will be used by the Python extension for that workspace.
Note: If you select an interpreter without a workspace folder open, VS Code sets python.defaultInterpreterPath in User scope instead, which sets the default interpreter for VS Code in general. The user setting makes sure you always have a default interpreter for Python projects. The workspace settings lets you override the user setting.
Create a Python Hello World source code file
From the File Explorer toolbar, select the New File button on the hello folder:
Name the file hello.py , and it automatically opens in the editor:
By using the .py file extension, you tell VS Code to interpret this file as a Python program, so that it evaluates the contents with the Python extension and the selected interpreter.
Note: The File Explorer toolbar also allows you to create folders within your workspace to better organize your code. You can use the New folder button to quickly create a folder.
Now that you have a code file in your Workspace, enter the following source code in hello.py :
When you start typing print , notice how IntelliSense presents auto-completion options.
IntelliSense and auto-completions work for standard Python modules as well as other packages you've installed into the environment of the selected Python interpreter. It also provides completions for methods available on object types. For example, because the msg variable contains a string, IntelliSense provides string methods when you type msg. :
Feel free to experiment with IntelliSense some more, but then revert your changes so you have only the msg variable and the print call, and save the file ( ⌘S (Windows, Linux Ctrl+S ) ).
For full details on editing, formatting, and refactoring, see Editing code. The Python extension also has full support for Linting.
Run Hello World
It's simple to run hello.py with Python. Just click the Run Python File in Terminal play button in the top-right side of the editor.
The button opens a terminal panel in which your Python interpreter is automatically activated, then runs python3 hello.py (macOS/Linux) or python hello.py (Windows):
There are three other ways you can run Python code within VS Code:
Right-click anywhere in the editor window and select Run Python File in Terminal (which saves the file automatically):
Select one or more lines, then press Shift+Enter or right-click and select Run Selection/Line in Python Terminal. This command is convenient for testing just a part of a file.
From the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), select the Python: Start REPL command to open a REPL terminal for the currently selected Python interpreter. In the REPL, you can then enter and run lines of code one at a time.
Configure and run the debugger
Let's now try debugging our simple Hello World program.
First, set a breakpoint on line 2 of hello.py by placing the cursor on the print call and pressing F9 . Alternately, just click in the editor's left gutter, next to the line numbers. When you set a breakpoint, a red circle appears in the gutter.
Next, to initialize the debugger, press F5 . Since this is your first time debugging this file, a configuration menu will open from the Command Palette allowing you to select the type of debug configuration you would like for the opened file.
Note: VS Code uses JSON files for all of its various configurations; launch.json is the standard name for a file containing debugging configurations.
These different configurations are fully explained in Debugging configurations; for now, just select Python File, which is the configuration that runs the current file shown in the editor using the currently selected Python interpreter.
You can also start the debugger by clicking on the down-arrow next to the run button on the editor, and selecting Debug Python File in Terminal.
The debugger will stop at the first line of the file breakpoint. The current line is indicated with a yellow arrow in the left margin. If you examine the Local variables window at this point, you will see now defined msg variable appears in the Local pane.
A debug toolbar appears along the top with the following commands from left to right: continue ( F5 ), step over ( F10 ), step into ( F11 ), step out ( ⇧F11 (Windows, Linux Shift+F11 ) ), restart ( ⇧⌘F5 (Windows, Linux Ctrl+Shift+F5 ) ), and stop ( ⇧F5 (Windows, Linux Shift+F5 ) ).
The Status Bar also changes color (orange in many themes) to indicate that you're in debug mode. The Python Debug Console also appears automatically in the lower right panel to show the commands being run, along with the program output.
To continue running the program, select the continue command on the debug toolbar ( F5 ). The debugger runs the program to the end.
Tip Debugging information can also be seen by hovering over code, such as variables. In the case of msg , hovering over the variable will display the string Hello world in a box above the variable.
You can also work with variables in the Debug Console (If you don't see it, select Debug Console in the lower right area of VS Code, or select it from the . menu.) Then try entering the following lines, one by one, at the > prompt at the bottom of the console:
Select the blue Continue button on the toolbar again (or press F5) to run the program to completion. "Hello World" appears in the Python Debug Console if you switch back to it, and VS Code exits debugging mode once the program is complete.
If you restart the debugger, the debugger again stops on the first breakpoint.
To stop running a program before it's complete, use the red square stop button on the debug toolbar ( ⇧F5 (Windows, Linux Shift+F5 ) ), or use the Run > Stop debugging menu command.
For full details, see Debugging configurations, which includes notes on how to use a specific Python interpreter for debugging.
Tip: Use Logpoints instead of print statements: Developers often litter source code with print statements to quickly inspect variables without necessarily stepping through each line of code in a debugger. In VS Code, you can instead use Logpoints. A Logpoint is like a breakpoint except that it logs a message to the console and doesn't stop the program. For more information, see Logpoints in the main VS Code debugging article.
Install and use packages
Let's now run an example that's a little more interesting. In Python, packages are how you obtain any number of useful code libraries, typically from PyPI. For this example, you use the matplotlib and numpy packages to create a graphical plot as is commonly done with data science. (Note that matplotlib cannot show graphs when running in the Windows Subsystem for Linux as it lacks the necessary UI support.)
Return to the Explorer view (the top-most icon on the left side, which shows files), create a new file called standardplot.py , and paste in the following source code:
Tip: If you enter the above code by hand, you may find that auto-completions change the names after the as keywords when you press Enter at the end of a line. To avoid this, type a space, then Enter .
Next, try running the file in the debugger using the "Python: Current file" configuration as described in the last section.
Unless you're using an Anaconda distribution or have previously installed the matplotlib package, you should see the message, "ModuleNotFoundError: No module named 'matplotlib'". Such a message indicates that the required package isn't available in your system.
To install the matplotlib package (which also installs numpy as a dependency), stop the debugger and use the Command Palette to run Terminal: Create New Terminal ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) ). This command opens a command prompt for your selected interpreter.
A best practice among Python developers is to avoid installing packages into a global interpreter environment. You instead use a project-specific virtual environment that contains a copy of a global interpreter. Once you activate that environment, any packages you then install are isolated from other environments. Such isolation reduces many complications that can arise from conflicting package versions. To create a virtual environment and install the required packages, enter the following commands as appropriate for your operating system:
Note: For additional information about virtual environments, see Environments.
Create and activate the virtual environment
Note: When you create a new virtual environment, you should be prompted by VS Code to set it as the default for your workspace folder. If selected, the environment will automatically be activated when you open a new terminal.
For Windows
If the activate command generates the message "Activate.ps1 is not digitally signed. You cannot run this script on the current system.", then you need to temporarily change the PowerShell execution policy to allow scripts to run (see About Execution Policies in the PowerShell documentation):
For macOS/Linux
Select your new environment by using the Python: Select Interpreter command from the Command Palette.
Install the packages
Rerun the program now (with or without the debugger) and after a few moments a plot window appears with the output:
Once you are finished, type deactivate in the terminal window to deactivate the virtual environment.
For additional examples of creating and activating a virtual environment and installing packages, see the Django tutorial and the Flask tutorial.
Next steps
You can configure VS Code to use any Python environment you have installed, including virtual and conda environments. You can also use a separate environment for debugging. For full details, see Environments.
To learn to build web apps with the Django and Flask frameworks, see the following tutorials:
Working with Python in Visual Studio Code, using the Microsoft Python extension, is simple, fun, and productive. The extension makes VS Code an excellent Python editor, and works on any operating system with a variety of Python interpreters. It leverages all of VS Code's power to provide auto complete and IntelliSense, linting, debugging, and unit testing, along with the ability to easily switch between Python environments, including virtual and conda environments.
This article provides only an overview of the different capabilities of the Python extension for VS Code. For a walkthrough of editing, running, and debugging code, use the button below.
Install Python and the Python extension
Once you have a version of Python installed, activate it using the Python: Select Interpreter command. If VS Code doesn't automatically locate the interpreter you're looking for, refer to Environments - Manually specify an interpreter.
You can configure the Python extension through settings. Learn more in the Python Settings reference.
Windows Subsystem for Linux: If you are on Windows, WSL is a great way to do Python development. You can run Linux distributions on Windows and Python is often already installed. When coupled with the Remote - WSL extension, you get full VS Code editing and debugging support while running in the context of WSL. To learn more, go to Developing in WSL or try the Working in WSL tutorial.
Run Python code
To experience Python, create a file (using the File Explorer) named hello.py and paste in the following code:
The Python extension then provides shortcuts to run Python code in the currently selected interpreter (Python: Select Interpreter in the Command Palette):
- In the text editor: right-click anywhere in the editor and select Run Python File in Terminal. If invoked on a selection, only that selection is run.
- In Explorer: right-click a Python file and select Run Python File in Terminal.
You can also use the Terminal: Create New Terminal command to create a terminal in which VS Code automatically activates the currently selected interpreter. See Environments below. The Python: Start REPL activates a terminal with the currently selected interpreter and then runs the Python REPL.
For a more specific walkthrough on running code, see the tutorial.
Autocomplete and IntelliSense
The Python extension supports code completion and IntelliSense using the currently selected interpreter. IntelliSense is a general term for a number of features, including intelligent code completion (in-context method and variable suggestions) across all your files and for built-in and third-party modules.
IntelliSense quickly shows methods, class members, and documentation as you type, and you can trigger completions at any time with ⌃Space (Windows, Linux Ctrl+Space ) . You can also hover over identifiers for more information about them.
Tip: Check out the IntelliCode extension for VS Code (preview). IntelliCode provides a set of AI-assisted capabilities for IntelliSense in Python, such as inferring the most relevant auto-completions based on the current code context.
Linting
Linting analyzes your Python code for potential errors, making it easy to navigate to and correct different problems.
The Python extension can apply a number of different linters including Pylint, pycodestyle, Flake8, mypy, pydocstyle, prospector, and pylama. See Linting.
Debugging
No more print statement debugging! Set breakpoints, inspect data, and use the debug console as you run your program step by step. Debug a number of different types of Python applications, including multi-threaded, web, and remote applications.
For Python-specific details, including setting up your launch.json configuration and remote debugging, see Debugging. General VS Code debugging information is found in the debugging document. The Django and Flask tutorials also demonstrate debugging in the context of those web apps, including debugging Django page templates.
Environments
The Python extension automatically detects Python interpreters that are installed in standard locations. It also detects conda environments as well as virtual environments in the workspace folder. See Configuring Python environments.
The current environment is shown on the left side of the VS Code Status Bar:
The Status Bar also indicates if no interpreter is selected:
The selected environment is used for IntelliSense, auto-completions, linting, formatting, and any other language-related feature other than debugging. It is also activated when you use run Python in a terminal.
To change the current interpreter, which includes switching to conda or virtual environments, select the interpreter name on the Status Bar or use the Python: Select Interpreter command.
VS Code prompts you with a list of detected environments as well as any you've added manually to your user settings (see Configuring Python environments).
Installing packages
Packages are installed using the Terminal panel and commands like pip install (Windows) and pip3 install (macOS/Linux). VS Code installs that package into your project along with its dependencies. Examples are given in the Python tutorial as well as the Django and Flask tutorials.
Jupyter notebooks
If you open a Jupyter notebook file ( .ipynb ) in VS Code, you can use the Jupyter Notebook Editor to directly view, modify, and run code cells.
Opening a notebook as a Python file allows you to use all of VS Code's debugging capabilities. You can then save the notebook file and open it again as a notebook in the Notebook Editor, Jupyter, or even upload it to a service like Azure Notebooks.
Using either method, Notebook Editor or a Python file, you can also connect to a remote Jupyter server for running the code. For more information, see Jupyter support.
Testing
The Python extension supports testing with unittest and pytest.
To run tests, you enable one of the frameworks in settings. Each framework also has specific settings, such as arguments that identify paths and patterns for test discovery.
Once discovered, VS Code provides a variety of commands (on the Status Bar, the Command Palette, and elsewhere) to run and debug tests, including the ability to run individual test files and individual methods.
Configuration
The Python extension provides a wide variety of settings for its various features. These are described on their relevant topics, such as Editing code, Linting, Debugging, and Testing. The complete list is found in the Settings reference.
Other popular Python extensions
The Microsoft Python extension provides all of the features described previously in this article. Additional Python language support can be added to VS Code by installing other popular Python extensions.
- Open the Extensions view ( ⇧⌘X (Windows, Linux Ctrl+Shift+X ) ).
- Filter the extension list by typing 'python'.
The extensions shown above are dynamically queried. Click on an extension tile above to read the description and reviews to decide which extension is best for you. See more in the Marketplace.
If I use the debug console, the version and path is right:
But the output always defaults to "python2.7", no matter what I do.
How can I fix this?
What does the lower-left corner say your interpreter is set to? If that doesn't point to the interpreter you are expecting then click on it and change it. If it does then please file an issue.
For myself on OSx my default interpreter in VS Code was zsh and defaulted to 2.7 . After changing interpreter to 3.6 & opening bash in VS Code all was well.
16 Answers 16
Under the view menu select 'show command pallet'. One of the commands you can then select from the command palette is 'Python: Select Interpreter'. Selecting this option will allow you to choose which version of python to use.
I tried this, but it didn't work. When I checked the python version in the terminal, it still said a different version than the interpreter I selected, in spite of starting a new instance of terminal.
I searched for hours and hours how to make my python code work on vscode, your answer took me all out, thank you so much!
I have done this 3 times. It does not work. Whatever the answer is, it is not 'Python: Select Interpreter'. I have Python 3.8 selected. But code chooses version 3.7.2. I have rebooted. It still chooses 3.7.2 . So whatever solution does this it is not simply using the command pallet. I can find the right version by copying what Code says and running it on the command line. But Code, does not run that command that it says it is supposed to.
If you type "python --help", you'll see "-u" flag stands for "unbuffered binary stdout and stderr. " - don't know why it matters here.
The solution here is to use Code-Runner's supported customized parameters, so you should change "python" line in it's settings.json to:
Thanks man, I changed mine to python3.9 and now it works like a charm. You don't know the many times I changed the interpreter to py3.9 and banged my keyboard in frustration. FRIGGIN code runner. There are like 5 python installations on my pc lol.
Thanks! I was pulling my hair out trying to figure out why the debug Run button used the correct interpreter (python3 from a virtual environment) but the regular (non-debug) Run used the first it found (python2).
Tot's answer is what worked for me on windows 10, with a few modifications.
- File -> Preferences -> Settings
- Type in "python.pythonPath" in the search bar.
- Change it to what you normally run python with from the command line. If you have your Path environment variable set, that's just python . If not, it's likely the full path to the executable.
This solution is for Mac and Linux:
To change your Python version from 2.7 to 3 do this:
In Vscode click on file > preferences > settings.
On the right side click on the . (the three dots) and select (open settings.json)
In the search bar type code-runner.executorMap.
You can only change the settings on the right side.
After the last setting type a comma then "code-runner.executorMap" and hit enter, this will copy all the settings from the default file.
Look for "python" and change the command next to it to "python3".
Save the changes and you should be good to go.
If you add a new line (press enter to create a blank line) before your first point you will see the output formatted correctly as the list you presumably intended
VS Code's terminal using a different python interpreter than the one you've selected
By default, it doesn't know about your interpreter, and will initialize using the default .bashrc or equivalent in the OS.
I found two relevant settings from an issue in Feb 2021. Checking the second option Python > Terminal: Activate Environment enables automatic activation of virtual environment:
In settings.json it is called "python.terminal.activateEnvironment": true .
Update (8 Aug 2021): Today when I opened the terminal from VS Code on Windows, it automatically inserted a line of code & C:/Users/[UserName]/[venv]/Scripts/Activate.ps1 to activate the appropriate environment associated with the selected python interpreter! It appears the aforementioned settings is now the default behavior. While there are changes to Terminal behavior in the release notes of July 2021 (version 1.59), I don't see virtual environment activation being explicitly mentioned.
The new behavior is documented here, in "Environments and Terminal windows".
"python.pythonPath" has been deprecated
Therefore most previous answers are outdated. Use "python.defaultInterpreterPath" instead:
If you wish to set a default python interpreter for all workspaces, open settings with Ctrl+Shift+P , Preferences: Open User Settings and search for Python: Default Interpreter Path . Otherwise, if you want to set it for only the current workspace, use Preferences: Open Workspace Settings instead.
In your case, you wish to set it to $/env/bin/python3.6 . If you edit settings.json directly instead of using the GUI:
Detailed instructions can be found in the documentation "Manually specify an interpreter", including using environment variables as the interpreter's path.
Весь код в проекте Python выполняется в контексте определенного окружения, например в глобальном окружении Python, окружении Anaconda, виртуальном окружении или окружении Conda. Visual Studio использует это же окружение для отладки, импорта, автозавершения элементов, проверки синтаксиса и других задач, требующих языковые службы, которые характерны для данной версии Python и набора установленных пакетов.
Для всех новых проектов Python в Visual Studio настраивается глобальное окружение по умолчанию, которое указано в узле Окружения Python в обозревателе решений:
Чтобы изменить окружение для проекта, щелкните правой кнопкой мыши узел Окружения Python и выберите Добавление и удаление окружений Python. В появившемся списке глобальных, виртуальных окружений и окружений Conda выберите все окружения, которые должны отображаться в узле Окружения Python:
Когда вы щелкнете ОК, все выбранные окружения отобразятся в узле Окружения Python. Полужирным шрифтом здесь выделено окружение, которое сейчас активно:
Чтобы быстро активировать другое окружение, щелкните его имя правой кнопкой мыши и выберите команду Активировать окружение. Ваш выбор сохраняется в проекте, и выбранное окружение применяется при каждом последующем открытии проекта. Если вы снимете все флажки в диалоговом окне Добавление и удаление окружений Python, в Visual Studio будет активировано глобальное окружение по умолчанию.
В контекстном меню узла Окружения Python также доступны дополнительные команды:
Команда | Описание |
---|---|
Добавить виртуальное окружение | Запускает процесс создания виртуального окружения в проекте. Дополнительные сведения см. в разделе Создание виртуального окружения. |
Добавить существующее виртуальное окружение | Выводит запрос на выбор папки, содержащей виртуальное окружение, и добавляет окружение в список в узле Окружения Python, но не активирует его. См. дополнительные сведения об активации существующего виртуального окружения. |
Создать окружение Conda | Переключается в окно Окружения Python, в котором нужно ввести имя окружения и указать для него базовый интерпретатор. См. Окружения Conda. |
Чтобы изменить окружение для проекта, щелкните правой кнопкой мыши узел Окружения Python и выберите Добавить окружение. Можно также выбрать пункт Добавить окружение в раскрывающемся списке сред на панели инструментов Python.
Когда откроется диалоговое окно Добавление окружения, перейдите на вкладку Существующее окружение и выберите новое окружение из раскрывающегося списка Окружение:
Если вы уже добавили в проект окружение, отличное от стандартного глобального окружения, для него может потребоваться активация. Щелкните окружение правой кнопкой мыши в узле Окружения Python и выберите действие Активировать окружение. Чтобы удалить из проекта окружение, выберите действие Удалить.
Использование виртуальных окружений
Виртуальное окружение — это уникальное сочетание интерпретатора Python и набора библиотек, которое не повторяется в других глобальных окружениях и окружениях Conda. Виртуальное окружение предназначено для конкретного проекта, и данные о нем хранятся в папке проекта. В этой папке содержатся установленные библиотеки окружения и файл pyvenv.cfg, в котором указан путь к базовому интерпретатору, расположенному в другом месте файловой системы. То есть в виртуальном окружении нет копии интерпретатора, а только ссылка на него.
Преимуществом виртуального окружения является то, что в нем по мере разработки проекта всегда будут отражаться точные зависимости проекта. (С другой стороны, в общем глобальном окружении можно хранить любое число библиотек, используемых или неиспользуемых в проекте.) В виртуальном окружении можно легко создать файл requirements.txt, который будет использоваться для переустановки этих зависимостей на другой рабочий компьютер или компьютер разработки. Дополнительные сведения см. в руководстве по управлению необходимыми пакетами с помощью requirements.txt.
Если в Visual Studio открыть проект, который содержит файл requirements.txt, Visual Studio автоматически позволит воссоздать виртуальное окружение. На тех компьютерах, где не установлена среда Visual Studio, можно восстанавливать пакеты с помощью команды pip install -r requirements.txt .
Учитывая то, что в виртуальном окружении жестко запрограммирован путь к базовому интерпретатору и можно воссоздать окружение с помощью файла requirements.txt, обычно вся папка виртуального окружения не указывается в системе управления версиями.
В следующих разделах объясняется, как активировать существующее виртуальное окружение в проекте и создать новое виртуальное окружение.
В Visual Studio виртуальное окружение для проекта активируется так же, как и любое другое окружение: с помощью узла Окружения Python в обозревателе решений.
Если виртуальное окружение добавлено в проект, оно появится в окне Окружения Python. После этого вы сможете активировать его, как и любое другое окружение, и управлять его пакетами.
Создание виртуальной среды
Виртуальное окружение можно создать напрямую в Visual Studio, выполнив следующие действия.
В обозревателе решений выберите Добавить виртуальное окружение, щелкнув правой кнопкой мыши Окружения Python. Откроется следующее диалоговое окно:
В поле Расположение виртуального окружения укажите путь к виртуальному окружению. Если вы укажете только имя, для виртуального окружения в текущем проекте создается вложенная папка с таким же именем.
Выберите среду в качестве базового интерпретатора и щелкните Создать. В Visual Studio отобразится индикатор выполнения, который позволяет отслеживать процесс настройки окружения и скачивания необходимых пакетов. После завершения процесса виртуальное окружение отобразится в окне Окружения Python для проекта, в котором оно размещено.
Виртуальное окружение не активируется по умолчанию. Чтобы активировать виртуальное окружение для проекта, щелкните проект правой кнопкой мыши и выберите Активировать окружение.
Если указан путь к расположению существующего виртуального окружения, Visual Studio автоматически обнаруживает базовый интерпретатор (для этого используется файл orig-prefix.txt в каталоге окружения lib). Вместо кнопки Создать отобразится кнопка Добавить.
Если в добавляемом виртуальном окружении уже есть файл requirements.txt, в диалоговом окне Добавление виртуального окружения отображается запрос на автоматическую установку пакетов. Этот механизм упрощает восстановление окружения на другом компьютере:
В любом случае результат будет такой же, как и при добавлении существующего виртуального окружения.
Активация существующего виртуального окружения
Если у вас уже есть виртуальное окружение, его можно активировать для проекта следующим образом:
В обозревателе решений выберите Добавить существующее виртуальное окружение, щелкнув правой кнопкой мыши Окружения Python.
Откроется диалоговое окно Обзор. Найдите и выберите здесь папку с виртуальным окружением, а затем нажмите кнопку ОК. Если Visual Studio обнаружит в этом окружении файл requirements.txt, появится запрос на установку обнаруженных пакетов.
Через несколько секунд виртуальное окружение появится в узле Окружения Python****обозревателя решений. Виртуальное окружение не активируется по умолчанию, поэтому щелкните его правой кнопкой мыши и выберите действие Активировать окружение.
Создание виртуальной среды
Виртуальное окружение можно создать напрямую в Visual Studio, выполнив следующие действия.
Чтобы изменить окружение для проекта, щелкните правой кнопкой мыши узел Окружения Python в обозревателе решений и выберите Добавить окружение или выберите Добавить окружение из раскрывающегося списка окружений на панели инструментов Python. В открывшемся диалоговом окне Добавление окружения выберите вкладку Виртуальное окружение:
Укажите имя виртуального окружения, выберите базовый интерпретатор и проверьте его расположение. В разделе Install packages from file (Устанавливать пакеты из файла) укажите путь к файлу requirements.txt, если нужно.
Проверьте другие параметры в диалоговом окне.
Выберите Создать, чтобы завершить создание виртуального окружения. В Visual Studio отобразится индикатор выполнения, который позволяет отслеживать процесс настройки окружения и скачивания необходимых пакетов. После завершения процесса виртуальное окружение активируется и отображается в узле Окружения Python в обозревателе решений и в окне Окружения Python для проекта, в который оно включено.
Активация существующего виртуального окружения
Если у вас уже есть виртуальное окружение, его можно активировать для проекта следующим образом:
В обозревателе решений щелкните правой кнопкой мыши Окружения Python и выберите Добавить окружение.
Откроется диалоговое окно Обзор. Найдите и выберите здесь папку с виртуальным окружением, а затем нажмите кнопку ОК. Если Visual Studio обнаружит в этом окружении файл requirements.txt, появится запрос на установку обнаруженных пакетов.
Через несколько секунд виртуальное окружение появится в узле Окружения Python****обозревателя решений. Виртуальное окружение не активируется по умолчанию, поэтому щелкните его правой кнопкой мыши и выберите действие Активировать окружение.
Удаление виртуального окружения
В обозревателе решений щелкните правой кнопкой мыши виртуальное окружение и выберите Удалить.
В Visual Studio вам будет предложено выбрать нужное действие (убрать или удалить виртуальное окружение). Вариант Убрать означает, что окружение исчезнет из проекта, но сохранится в файловой системе. Если выбрать Удалить, окружение убирается из проекта и все его файлы удаляются из файловой системы. Это действие не затрагивает базовый интерпретатор.
Просмотр установленных пакетов
В Обозревателе решений можно развернуть узел любого окружения, чтобы быстро просмотреть установленные в нем пакеты (те, которые можно импортировать и применять в коде, когда активно это окружение):
Чтобы установить пакеты, щелкните окружение правой кнопкой мыши и выберите действие Установить пакет Python. В окне Окружения Python откроется соответствующая вкладка Пакеты. Введите условие поиска (лучше всего имя пакета), и в Visual Studio отобразятся все подходящие пакеты.
Чтобы установить новые пакеты, щелкните окружение правой кнопкой мыши и выберите действие Manage Python Packages (Управление пакетами Python). В окне Окружения Python откроется соответствующая вкладка Пакеты. На вкладке Пакеты введите условие поиска (обычно это имя пакета), и Visual Studio отобразит все подходящие пакеты.
Пакеты (и зависимости) в Visual Studio для большинства окружений скачиваются из репозитория Python Package Index (PyPI). В нем же вы можете искать доступные пакеты. В строке состояния Visual Studio и окне вывода отображаются сведения об установке. Чтобы удалить пакет, щелкните его правой кнопкой мыши и выберите Удалить.
Не забывайте, что отображаемые записи могут быть неточными, а задания установки и удаления — ненадежными или недоступными. Visual Studio использует диспетчер пакетов pip, если он доступен, и при необходимости скачивает и устанавливает его. Visual Studio также может использовать диспетчер пакетов простой установки (easy_install). Здесь же отображаются пакеты, установленные с помощью команд pip или easy_install из командной строки.
Обратите внимание, что сейчас Visual Studio не поддерживает использование conda для установки пакетов в окружении Conda. Вместо этого используйте conda из командной строки.
Читайте также: