Настройка visual studio code python
Настройка visual studio code python
Python Developer Tools от Microsoft. Начало работы
Последние несколько лет специалисты Microsoft трудились над тем, чтобы добавить поддержку инструментов разработчика Python в одни из наших самых популярных продуктов: Visual Studio Code и Visual Studio. В этом году все заработало. В статье мы познакомимся с инструментами разработчика Python в Visual Studio, Visual Studio Code, Azure и т. д. Заглядывайте под кат!
Python — один из самых быстро развивающихся языков программирования, к которому обращаются как начинающие, так и опытные разработчики. Его популярность обусловлена легкой в освоении семантикой и широким спектром применения, начиная от написания скриптов и заканчивая созданием веб-сервисов и моделей машинного обучения.
Дополнительную информацию и последние новости о Python в Microsoft вы можете найти в блоге Python at Microsoft.
Visual Studio Code
Расширение Python для Visual Studio Code с открытым исходным кодом включает в себя другие общедоступные пакеты Python, чтобы предоставить разработчикам широкие возможности для редактирования, отладки и тестирования кода. Python — самый быстроразвивающийся язык в Visual Studio Code, а соответствующее расширение является одним из самых популярных в разделе Marketplace, посвященном Visual Studio Code!
Чтобы начать работу с расширением, необходимо сначала скачать Visual Studio Code, а затем, следуя нашему руководству Начало работы с Python, установить расширение и настроить основные функции. Рассмотрим некоторые из них.
Прежде всего необходимо убедиться, что Visual Studio Code использует правильный интерпретатор Python. Чтобы сменить интерпретатор, достаточно выбрать нужную версию Python в строке состояния:
Селектор поддерживает множество разных интерпретаторов и сред Python: Python 2, 3, virtualenv, Anaconda, Pipenv и pyenv. После выбора интерпретатора расширение начнет использовать его для функции IntelliSense, рефакторинга, анализа, выполнения и отладки кода.
Чтобы локально запустить скрипт Python, можно воспользоваться командой «Python: Create Terminal» («Python: создать терминал») для создания терминала с активированной средой. Нажмите CTRL + Shift + P (или CMD + Shift + P на Mac), чтобы открыть командную строку. Чтобы выполнить файл Python, достаточно щелкнуть на нем правой кнопкой мыши и выбрать пункт «Run Python File in Terminal» («Запустить файл Python в терминале»):
Эта команда запустит выбранный интерпретатор Python, в данном случае виртуальную среду Python 3.6, для выполнения файла:
Расширение Python также включает шаблоны отладки для многих популярных типов приложений. Перейдите на вкладку «Debug» («Отладка») и выберите «Add Configuration…» («Добавить конфигурацию. ») в выпадающем меню конфигурации отладки:
Вы увидите готовые конфигурации для отладки текущего файла, подключающегося к удаленному серверу отладки или соответствующему приложению Flask, Django, Pyramid, PySpark или Scrapy. Для запуска отладки нужно выбрать конфигурацию и нажать зеленую кнопку Play (или клавишу F5 на клавиатуре, FN + F5 на Mac).
Расширение Python поддерживает различные анализаторы кода, для которых можно настроить запуск после сохранения файла Python. PyLint включен по умолчанию, а другой анализатор можно выбрать с помощью команды «Python: Select Linter» («Python: выбрать анализатор кода»):
Это еще не все: предусмотрена поддержка рефакторинга, а также модульного тестирования с помощью unittest, pytest и nose. К тому же вы можете использовать Visual Studio Live Share для удаленной работы над кодом Python вместе с другими разработчиками!
Python в Visual Studio
Visual Studio поддерживает большую часть функций Visual Studio Code, но также предлагает все полезные возможности интегрированной среды разработки, что позволяет совершать больше операций без использования командной строки. Visual Studio также предоставляет не имеющие равных возможности для работы с гибридными проектами Python и C# или C++.
Чтобы включить поддержку Python в Visual Studio на Windows, необходимо выбрать рабочую нагрузку «Разработка на Python» и (или) рабочую нагрузку «Приложения для обработки и анализа данных и аналитические приложения» в установщике Visual Studio:
Можно установить различные версии Python и Anaconda, выбрав их в меню дополнительных компонентов (см. правую часть скриншота выше).
Чтобы создать приложение с нуля, откройте шаблон приложения Python и приступайте к написанию кода. Также можно создать проект, взяв за основу существующий код Python или используя веб-шаблоны для Flask, Django и Bottle. Ознакомьтесь с нашим Руководством по Flask и Руководством по Django, чтобы получить подробную информацию по разработке веб-приложений с помощью этих платформ и Visual Studio.
Если установлена рабочая нагрузка по обработке и анализу данных, также можно использовать шаблоны для проектов по машинному обучению с использованием Tensorflow и CNTK.
После того как проект создан, управлять виртуальными средами и средами conda можно с помощью узла «Python Environments» («Среды Python») в обозревателе решений и окне среды Python. Щелкнув правой кнопкой мыши по активной среде Python и выбрав соответствующий пункт меню, можно установить дополнительные пакеты:
Можно даже проводить отладку кода на обоих языках в рамках одного сеанса, например, переключившись с типа отладки C++ на Python/Native:
Ознакомиться с подробной информацией о вставке Python в приложения C++ можно в публикации Вставка Python в проект C++ в блоге Python.
Кроме того, Visual Studio включает профилировщик Python и поддерживает модульное тестирование Python в Обозревателе тестов.
Python в Azure
Пакет Azure SDK для Python позволяет создавать службы в Azure, управлять ими и взаимодействовать с ними. Командная строка Azure CLI написана на Python, поэтому почти все, что она позволяет сделать, вы можете также выполнить на программном уровне с помощью пакета Python SDK.
Можно устанавливать отдельные библиотеки, например для установки пакета SDK для взаимодействия с Azure Storage воспользуйтесь командой:
Рекомендуется устанавливать только нужные вам пакеты, но для удобства вы можете установить весь набор пакетов Azure SDK, выполнив следующую команду:
После установки пакета SDK вы получаете доступ ко множеству полезных служб, начиная от использования API машинного обучения с помощью Azure Cognitive Services и заканчивая размещением глобально распределенных данных с помощью Azure Cosmos DB.
Веб-приложения можно развернуть с помощью функции Azure «Веб-приложение для контейнеров». Ознакомьтесь с видео From Zero to Azure with Python and Visual Studio Code (В Azure с нуля с помощью Python и Visual Studio Code), предоставляющим всю необходимую информацию по развертыванию приложений Flask с использованием Visual Studio Code. Также обратите внимание на краткое пособие по развертыванию приложения Flask с использованием командной строки.
Кроме того, на Azure можно запускать свободно размещенные блокноты Jupyter, поэтому локальная установка Jupyter не потребуется. К блокнотам Jupyter можно открывать доступ для их совместного использования. Например, вы можете просмотреть находящийся в общем доступе блокнот для создания рукописного текста с помощью машинного обучения:
Войдите в учетную запись на notebooks.azure.com, чтобы опробовать клонирование и запуск блокнотов Jupyter!
Полезные материалы по теме
Мини-книга «Создавайте более качественные приложения и быстро используйте данные там, где это нужно»
Читайте электронную книгу Создание современных приложений на основе больших данных в глобальном масштабе, чтобы узнать, как готовая к использованию глобально распределенная служба баз данных Azure Cosmos DB меняет подходы к управлению данными. Обеспечивайте доступность, согласованность и защиту данных, используя передовые отраслевые технологии корпоративного класса для соблюдения нормативных требований и обеспечения безопасности. Начните разработку лучших приложений для своих пользователей на базе одной из пяти четко определенных моделей согласованности.
Семинар «Как выбрать правильную инфраструктуру для выполнения ваших рабочих нагрузок в Azure»
В этом семинаре присоединитесь к рассказу регионального директора Microsoft Эрику Бойду, MVP Azure, о том, как выбрать правильные виртуальные машины, хранилища и сети для приложений и рабочих нагрузок в Azure.
Руководство по архитектуре облачных приложений
Используйте структурированный подход к разработке облачных приложений. В этой 300-страничной электронной книге об архитектуре облачных вычислений рассматриваются рекомендации по архитектуре, разработке и внедрению, которые применяются независимо от выбранной облачной платформы. В это руководство включены шаги по:
Coding Pack for Python
The Coding Pack for Python helps you quickly set up a Python coding environment with Visual Studio Code. The standalone installer helps you install a Python interpreter, Visual Studio Code, extensions that provide support for Python in Visual Studio Code, and a number of common and useful Python packages.
Getting started
With the Coding Pack for Python, it’s easy to get started developing with Python and VS Code.
Download and run the Coding Pack for Python installer.
Note: The installer only supports Windows 10 64-bit. This download is 200MB, and up to 100MB will be downloaded while you are installing.
Once the installer launches, review and accept the License Agreement. Then select Install.
After installation completes, select Next.
Note: If you select Cancel before the installation completes, you will need to manually remove and uninstall any components that have already been installed.
Launch Visual Studio Code and start coding!
Note: If there are any issues installing components, you can use the steps discussed in Manual installation
What’s installed by the Coding Pack for Python
The Coding Pack for Python installs the key components you need to use Visual Studio Code for Python development. Specifically, it installs:
Along with the tools and packages necessary for Python development, the Coding Pack also configures common user settings and PowerShell. This includes Python extension settings, such as the default interpreter and language server, as well as execution policies to allow for virtual environment activation in the terminal.
Note: If there was an existing version of Visual Studio Code installed on your machine, your settings.json will not be overwritten and you’ll need to configure Python settings yourself.
Manual installation
If you have any problems during installation, the following manual steps can be used to complete your installation.
Visual Studio Code and the Python extension
If there was an issue installing VS Code, you can install it from here.
Once VS Code is installed, you can install the Python extension for VS Code from the Visual Studio Marketplace. For additional details about installing extensions, see Extension Marketplace. The Python extension is named Python and is published by Microsoft.
Python interpreter
If there was an issue installing the Python interpreter, you can install Python 3.8 from the Microsoft Store. Along with the Python extension, you need to install a Python interpreter for development with Python. There are other options for installing the Python interpreter, such as directly from Python.org, and which interpreter you use is dependent on your specific needs. If you use the Python.org version, just make sure to uncheck the «Install launcher for all users» box if you don’t have admin access.
Note: If you use the Microsoft Store installation option, be aware that some packages might not work well with this package; however, the packages listed below have been tested and work fine.
For additional information about using Python on Windows, see the VS Code Python documentation and Using Python on Windows at Python.org.
Additional VS Code extensions
Pylance language server extension
Pylance is an extension that works alongside Python in Visual Studio Code to provide performant language support. Under the hood, Pylance is powered by Pyright, Microsoft’s static type checking tool. Using Pyright, Pylance can supercharge your Python IntelliSense experience with rich type information, helping you write better code faster.
Gather extension
The Gather extension adds the experimental Gather feature to the Python extension. With one button, you’ll be able to select any notebook or Interactive Window cell and have Gather find and then copy all of the dependent code that was used to generate that cell’s result into a new notebook or script.
Live Share extension
Visual Studio Live Share enables you to collaboratively edit and debug with others in real time, regardless of what programming languages you’re using or app types you’re building. It allows you to instantly share your current project, and then as needed, share debugging sessions, terminal instances, localhost web apps, voice calls, and more! For additional details, see the documentation.
Common Python packages
If you need to manually install the Python packages that the Coding Pack would otherwise have installed, you can do so using the following Python commands.
Be aware that these commands will install the packages into the global environment for your interpreter, because that’s where the Coding Pack would have installed them. That said, a good option to consider is adding the packages to a virtual environment. For information about virtual environments, see the topic Using Python environments in VS Code.
Note: If you have problems running the Python commands above, you might need to make sure that the Python interpreter is on your PATH environment variable.
Settings and configuration
To help you get started quickly, the Coding Pack for Python sets a few key settings. If you need to configure them manually, you can use the following guidance.
Set default interpreter
Set language server to pylance
Enable running scripts in PowerShell
Uninstalling the Coding Pack for Python
If you need to uninstall (or repair) your Coding Pack for Python installation, you can use the following steps.
Rerun the standalone installer.
At the UI prompt, select Uninstall.
Once you select uninstall, the following tasks will be performed:
Note: The uninstall process will not remove Visual Studio Code. At the end of the uninstall process, you can click the provided link to open «Apps & features» to uninstall Visual Studio Code. If you decide to repair your installation, be aware that any other Python packages you might have installed will be removed as part of the repair process.
Редактирование кода Python
Так как при разработке вы много работаете в редакторе кода, поддержка Python в Visual Studio предоставляет соответствующие функции для повышения продуктивности этой работы. К ним относятся выделение синтаксиса IntelliSense, автозавершение, справка по сигнатурам, переопределения методов, а также поиск и навигация.
Редактор также интегрируется с интерактивным окном в Visual Studio, упрощая обмен кодом между ними. Подробные сведения см. в разделах Учебник, шаг 3. Использование интерактивного окна REPL и Использование интерактивного окна. Команда «Отправить в интерактивное окно».
Общие сведения о редактировании кода в Visual Studio см. в статье Возможности редактора кода. Ознакомьтесь также со статьей Структура, чтобы узнать, как сконцентрироваться на определенных разделах кода.
Кроме того, с помощью обозревателя объектов Visual Studio (Вид>Другие окна>Обозреватель объектов или клавиши CTRL+W>J) вы можете проверять классы Python, определенные в каждом модуле, и функции, определенные в этих классах.
технология IntelliSense
Технология IntelliSense предоставляет следующие возможности: автозавершения, справка по сигнатурам, вывод кратких сведений и цветовая маркировка синтаксиса. Visual Studio 2017 версии 15.7 и более поздней также поддерживает подсказки по типам.
Для улучшения производительности функция IntelliSense в Visual Studio 2017 версии 15.5 и более ранних учитывает базу данных завершения, которая создается для каждого окружения Python в проекте. После добавления, удаления или обновления пакетов может потребоваться обновить базы данных. Их состояние отображается в окне Окружения Python (элемент того же уровня, что и обозреватель решений) на вкладке IntelliSense (см. дополнительные сведения об окне «Окружения»).
Visual Studio 2017 версии 15.6 и более поздних разными способами предоставляет функцию завершения IntelliSense, которая не зависит от базы данных.
Автозавершения
Автозавершения отображаются как операторы, идентификаторы и другие атрибуты, которые можно ввести в текущее расположение в редакторе. Автозавершения, отображаемые в списке, основываются на контексте, а также фильтруются для пропуска неправильных или ненужных параметров. Они часто инициируются при вводе различных инструкций (например, import ) и операторов (включая точку). Но их также можно отобразить в любое время, нажав клавиши CTRL+J>ПРОБЕЛ.
В открытом списке автозавершений можно выполнить поиск необходимого автозавершения с помощью клавиш со стрелками, мыши или путем ввода. Чем больше букв вы вводите, чем точнее фильтруется список для отображения возможных автозавершений. Кроме того, можно использовать следующие ярлыки:
Завершения элементов автоматически отображаются при вводе точки после переменной или значения. Вместе с ними отображаются методы и атрибуты потенциальных типов. Если переменная может быть нескольких типов, в списке содержатся все возможные варианты для всех типов с дополнительными сведениями для указания типов, поддерживающих каждое автозавершение. Если автозавершение поддерживается всеми возможными типами, оно отображается без заметки.
Элементы, которые начинаются и заканчиваются двумя символами подчеркивания, не отображаются по умолчанию. В общем случае к таким элементам не следует обращаться напрямую. Если же элемент нужен, введя два начальных символа подчеркивания, можно добавить эти завершения в список:
При использовании операторов raise и except отображаются списки классов, которые могут быть типами ошибок. При этом необязательно выводятся все определяемые пользователем исключения, но с их помощью можно быстро найти подходящие встроенные исключения.
При вводе символа @ запускается декоратор и отображаются потенциальные декораторы. Многие из этих элементов невозможно использовать в качестве декораторов. Чтобы определить, какие именно из них следует использовать, обратитесь к документации по библиотеке.
Вы можете настроить поведение автозавершений, выбрав Инструменты>Параметры>Текстовый редактор>Python>Дополнительно. Параметр Фильтрация списка по поисковой строке позволяет применить фильтрацию предложений автозавершения при вводе (флажок установлен по умолчанию), а при выборе параметра Завершение членов отображает пересечение членов отображаются только те автозавершения, которые поддерживают все возможные типы (флажок снят по умолчанию). См. раздел Параметры. Результаты завершения.
Подсказки по типам
Visual Studio 2017 версии 15.7 и более поздней.
Подсказки по типам в Python 3.5+ (PEP 484 (python.org) — это синтаксис аннотаций для функций и классов, который указывает на типы аргументов, возвращаемых значений и атрибутов класса. IntelliSense отображает подсказки по типам при наведении курсора на вызовы функций, аргументы и переменные с этими аннотациями.
В следующем примере можно увидеть, как аннотированные атрибуты класса Employee отображаются во всплывающем окне завершения IntelliSense для атрибута:
Полезно проверять подсказки по типам на протяжении проекта, поскольку ошибки обычно не возникают до выполнения. Для этой цели Visual Studio интегрирует стандартное средство MyPy через команду контекстного меню Python>Run Mypy в обозревателе решений:
При запуске команды отображается запрос на установку пакета mypy при необходимости. Затем Visual Studio запускает mypy для проверки подсказок по типам в каждом файле Python в проекте. Ошибки отображаются в окне Список ошибок в Visual Studio. При выборе элемента в окне вы перейдете к соответствующей строке в коде.
Использование команды Run Mypy в этом коде вызывает следующую ошибку:
В версиях Python, предшествующих 3.5, в Visual Studio также отображаются подсказки по типам, которые вы предоставляете через файлы-заглушки (.pyi). Файлы заглушки можно использовать всякий раз, когда вы не хотите включать подсказки по типам в код напрямую или необходимо создать подсказки по типам для библиотеки, которая не использует их напрямую. Дополнительные сведения см. в разделе Создание заглушек для модулей Python на вики-сайте проекта mypy.
Visual Studio содержит набор пакетов файлов Typeshed для Python 2 и 3, поэтому нет необходимости скачивать их отдельно. Но если вы хотите использовать другой набор файлов, можно указать путь в меню Средства>Параметры>Python>Языковой сервер. См. статью Параметры для Python в Visual Studio.
В настоящее время Visual Studio не поддерживает подсказки по типам в комментариях.
Справка по сигнатурам
Во время написания кода, вызывающего функцию, при вводе открывающейся скобки ( отображается справка по сигнатурам, а также доступные сведения о параметрах и документации. Ее также можно отобразить внутри вызова функции, нажав клавиши CTRL+SHIFT+ПРОБЕЛ. Хотя отображаемые сведения определяются строками документации в исходном коде функции, они содержат любые значения по умолчанию.
Чтобы отключить справку по сигнатурам, выберите Инструменты>Параметры>Текстовый редактор>Python>Общие и снимите флажок Завершение операторов>Сведения о параметрах.
Вывод кратких сведений
При наведении указателя мыши на идентификатор отображается подсказка. В зависимости от идентификатора в кратких сведениях могут отображаться потенциальные значения или типы, доступная документация, возвращаемые типы и расположения определений:
Цветовая маркировка синтаксиса
Цветовая маркировка синтаксиса — это функция, которая использует сведения, основанные на анализе кода, для выделения цветом переменных, операторов и других частей кода. Например, переменные, которые относятся к модулям или классам, могут выделяться другим цветом, нежели функции и остальные значения, а имена параметров могут отличаться цветом от локальных или глобальных переменных. (По умолчанию функции не выделяются полужирным шрифтом.)
Чтобы настроить цвета, выберите Инструменты>Параметры>Среда>Шрифты и цвета и измените записи Python в списке Отображение элементов.
Чтобы отключить цветовую маркировку синтаксиса, выберите Инструменты>Параметры>Текстовый редактор>Python>Дополнительно и снимите флажок Разные параметры>Имена цветов по типам. См. раздел Параметры. Прочие параметры.
Фрагменты кода
Фрагменты кода — это блоки, которые можно вставлять в файлы. Для этого введите сочетание клавиш и нажмите клавишу TAB или выберите команду Изменить>IntelliSense>Вставить фрагмент кода и Разместить во фрагменте, выберите Python, а затем нужный фрагмент кода.
Например, class является ярлыком для фрагмента кода, который вставляет определение класса. Вот фрагмент кода, который отображается в списке автозавершения при вводе class :
Если нажать клавишу TAB, будет создана остальная часть класса. Можно ввести имя и список базовых классов, перемещаясь между выделенными полями с помощью клавиши TAB, а затем нажав клавишу ВВОД, чтобы начать ввод текста.
Команды меню
При использовании команды меню Правка>IntelliSense>Вставить фрагмент кода сначала выберите Python, а затем — фрагмент кода:
Команда Правка>IntelliSense>Разместить во фрагменте точно так же помещает текущий выделенный фрагмент в текстовый редактор внутри выбранного структурного элемента. Предположим, у вас есть небольшой фрагмент кода:
Если выбрать этот код и команду Разместить во фрагменте, откроется список доступных фрагментов. Если выбрать def в списке, выбранный код будет помещен в определение функции. Вы сможете переходить между выделенным именем функции имя и аргументами с помощью клавиши TAB:
Просмотр доступных фрагментов кода
Доступные фрагменты кода можно просмотреть в диспетчере фрагментов кода. Чтобы открыть его, выберите пункт меню Инструменты>Диспетчер фрагментов кода и выберите Python в качестве языка:
Сведения о том, как создать собственные фрагменты кода, см. в статье Пошаговое руководство. Создание фрагмента кода.
Если вы написали качественный фрагмент кода, к которому вы хотите предоставить общий доступ, разместите его в репозитории и сообщите нам. Возможно, мы сможем включить его в следующий выпуск Visual Studio.
Навигация по коду
Поддержка Python в Visual Studio предоставляет несколько вариантов для быстрой навигации по коду, а также по библиотекам с доступным исходным кодом: Панель навигации, Перейти к определению, Перейти к и Найти все ссылки. Можно также использовать обозреватель объектов Visual Studio.
Панель переходов
Панель навигации отображается в верхней части каждого окна редактора и содержит двухуровневый список определений. Раскрывающийся список слева содержит определения классов и функций верхнего уровня в текущем файле. Раскрывающийся список справа отображает список определений в области, расположенной слева. При перемещении курсора в редакторе эти списки обновляются для отображения текущего контекста, при этом из них можно напрямую перейти к нужной записи.
Чтобы скрыть панель навигации, выберите Инструменты>Параметры>Текстовый редактор>Python>Общие и снимите флажок Параметры>Панель навигации.
Перейти к определению
Команда Перейти к определению позволяет быстро перейти от использования идентификатора (например, имени функции, класса или переменной) к определению в исходном коде. Ее можно вызвать, щелкнув правой кнопкой мыши идентификатор и выбрав Перейти к определению или поместив курсор внутрь этого идентификатора и нажав клавишу F12. Эта команда работает в коде и внешних библиотеках, если исходный код доступен. Если исходный код библиотеки недоступен, команда Перейти к определению переходит к соответствующему оператору import для ссылки на модуль или отображает ошибку.
Перейти к
Команда Правка>Перейти к (CTRL+, ) позволяет отобразить поле поиска в редакторе, где можно ввести любую строку и увидеть возможные совпадения в коде, определяющем функцию, класс или переменную. Она обеспечивает те же возможности, что и команда Перейти к определению, но без необходимости искать, где используется идентификатор.
Чтобы перейти к определению этого идентификатора, дважды щелкните любое имя или выберите его с помощью клавиш со стрелками и клавиши ВВОД.
Найти все ссылки
Найти все ссылки — это удобная команда для обнаружения, где используется и определен нужный идентификатор, включая операции импорта и назначения. Ее можно вызвать, щелкнув правой кнопкой мыши идентификатор и выбрав пункт Найти все ссылки или поместив курсор внутри этого идентификатора и нажав клавиши SHIFT+F12. Чтобы перейти к расположению элемента, нужно дважды щелкнуть его в списке.
Python Development in Visual Studio Code
Table of Contents
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Development in Visual Studio Code (Setup Guide)
One of the coolest code editors available to programmers, Visual Studio Code, is an open-source, extensible, light-weight editor available on all platforms. It’s these qualities that make Visual Studio Code from Microsoft very popular, and a great platform for Python development.
In this article, you’ll learn about Python development in Visual Studio Code, including how to:
We assume you are familiar with Python development and already have some form of Python installed on your system (Python 2.7, Python 3.6/3.7, Anaconda, or others). Screenshots and demos for Ubuntu and Windows are provided. Because Visual Studio Code runs on all major platforms, you may see slightly different UI elements and may need to modify certain commands.
If you already have a basic VS Code setup and you’re hoping to dig deeper than the goals in this tutorial, you might want to explore some advanced features in VS Code.
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
Installing and Configuring Visual Studio Code for Python Development
Installing Visual Studio Code is very accessible on any platform. Full instructions for Windows, Mac, and Linux are available, and the editor is updated monthly with new features and bug fixes. You can find everything at the Visual Studio Code website:
In case you were wondering, Visual Studio Code (or VS Code for short) shares almost nothing other than a name with its larger Windows-based namesake, Visual Studio.
Note: To learn how to set up VS Code as part of a full Python coding environment on a Windows machine, check out this comprehensive guide.
Visual Studio Code has built-in support for multiple languages and an extension model with a rich ecosystem of support for others. VS Code is updated monthly, and you can keep up to date at the Microsoft Python blog. Microsoft even makes the VS Code GitHub repo available for anyone to clone and contribute. (Cue the PR flood.)
The VS Code UI is well documented, so I won’t rehash it here:
Extensions for Python Development
As stated above, VS Code supports development in multiple programming languages through a well-documented extension model. The Python extension enables Python development in Visual Studio Code, with the following features:
Visual Studio Code extensions cover more than just programming language capabilities:
Keymaps allow users already familiar with Atom, Sublime Text, Emacs, Vim, PyCharm, or other environments to feel at home.
Themes customize the UI whether you like coding in the light, dark, or something more colorful.
Language packs provide a localized experience.
Here are some other extensions and settings I find useful:
GitLens provides tons of useful Git features directly in your editing window, including blame annotations and repository exploration features.
Auto save is easily turned on by selecting File, Auto Save from the menu. The default delay time is 1000 milliseconds, which is also configurable.
Settings Sync allows you to synchronize your VS Code settings across different installations using GitHub. If you work on different machines, this helps keep your environment consistent across them.
Of course, you may discover other useful extensions as you use VS Code. Please share your discoveries and settings in the comments!
Discovering and installing new extensions and themes is accessible by clicking on the Extensions icon on the Activity Bar. You can search for extensions using keywords, sort the results numerous ways, and install extensions quickly and easily. For this article, install the Python extension by typing python in the Extensions item on the Activity Bar, and clicking Install:
You can find and install any of the extensions mentioned above in the same manner.
Visual Studio Code Configuration Files
One important thing to mention is that Visual Studio Code is highly configurable through user and workspace settings.
Start a New Python Program
Let’s start our exploration of Python development in Visual Studio Code with a new Python program. In VS Code, type Ctrl + N to open a new File. (You can also select File, New from the menu.)
No matter how you get there, you should see a VS Code window that looks similar to the following:
Once a new file is opened, you can begin entering code.
Entering Python Code
For our test code, let’s quickly code up the Sieve of Eratosthenes (which finds all primes less than a given number). Begin typing the following code in the new tab you just opened:
You should see something similar to this:
Wait, what’s going on? Why isn’t Visual Studio Code doing any keyword highlighting, any auto-formatting, or anything really helpful? What gives?
That’s much better! VS Code automatically reformats the file as Python, which you can verify by inspecting the language mode in the lower left corner.
If you have multiple Python installations (like Python 2.7, Python 3.x, or Anaconda), you can change which Python interpreter VS Code uses by clicking the language mode indicator, or selecting Python: Select Interpreter from the Command Palette. VS Code supports formatting using pep8 by default, but you can select black or yapf if you wish.
Let’s add the rest of the Sieve code now. To see IntelliSense at work, type this code directly rather than cut and paste, and you should see something like this:
Here’s the full code for a basic Sieve of Eratosthenes:
As you type this code, VS Code automatically indents the lines under for and if statements for you properly, adds closing parentheses, and makes suggestions for you. That’s the power of IntelliSense working for you.
Running Python Code
Now that the code is complete, you can run it. There is no need to leave the editor to do this: Visual Studio Code can run this program directly in the editor. Save the file (using Ctrl + S ), then right-click in the editor window and select Run Python File in Terminal:
You should see the Terminal pane appear at the bottom of the window, with your code output showing.
Python Linting Support
You may have seen a pop up appear while you were typing, stating that linting was not available. You can quickly install linting support from that pop up, which defaults to PyLint. VS Code also supports other linters. Here’s the complete list at the time of this writing:
The Python linting page has complete details on how to setup each linter.
Note: The choice of linter is a project workspace setting, and not a global user setting.
Editing an Existing Python Project
In the Sieve of Eratosthenes example, you created a single Python file. That’s great as an example, but many times, you’ll create larger projects and work on them over a longer period of time. A typical new project work flow might look like this:
Using Visual Studio Code on a Python project (as opposed to a single Python file) opens up tons more functionality that lets VS Code truly shine. Let’s take a look at how it works with a larger project.
Late in the previous millennium, when I was a much younger programmer, I wrote a calculator program that parsed equations written in infix notation, using an adaptation of Edsger Dijkstra’s shunting yard algorithm.
To demonstrate the project-focused features of Visual Studio Code, I began recreating the shunting yard algorithm as an equation evaluation library in Python. To continue following along, feel free to clone the repo locally.
Once the folder is created locally, you can open the entire folder in VS Code quickly. My preferred method (as mentioned above) is modified as follows, since I already have the folder and basic files created:
For my equation eval library project, here’s what I see:
When Visual Studio Code opens the folder, it also opens the files you last had opened. (This is configurable.) You can open, edit, run, and debug any file listed. The Explorer view in the Activity Bar on the left gives you a view of all the files in the folder and shows how many unsaved files exist in the current set of tabs.
Testing Support
VS Code can automatically recognize existing Python tests written in the unittest framework, or the pytest or Nose frameworks if those frameworks are installed in the current environment. I have a unit test written in unittest for the equation eval library, which you can use for this example.
To run your existing unit tests, from any Python file in the project, right-click and select Run Current Unit Test File. You’ll be prompted to specify the test framework, where in the project to search for tests, and the filename pattern your tests utilize.
Once the test framework is set up and the tests have been discovered, you can run all your tests by clicking Run Tests on the Status Bar and selecting an option from the Command Palette:
You can even run individual tests by opening the test file in VS Code, clicking Run Tests on the Status Bar, and selecting the Run Unit Test Method… and the specific test to run. This makes it trivial to address individual test failures and re-run only failed tests, which is a huge time-saver! Test results are shown in the Output pane under Python Test Log.
Debugging Support
Even though VS Code is a code editor, debugging Python directly within VS Code is possible. VS Code offers many of the features you would expect from a good code debugger, including:
You can see them all as part of the Debug view on the Activity Bar:
The debugger can control Python apps running in the built-in terminal or an external terminal instance. It can attach to an already running Python instances, and can even debug Django and Flask apps.
Before you start debugging more complicated projects, including Django or Flask applications, you need to setup and then select a debug configuration. Setting up the debug configuration is relatively straightforward. From the Debug view, select the Configuration drop-down, then Add Configuration, and select Python:
You can even perform remote debugging, and debug Jinja and Django templates. Close the launch.json file in the editor and select the proper configuration for your application from the Configuration drop-down.
Git Integration
VS Code has built-in support for source control management, and ships with support for Git and GitHub right out of the box. You can install support for other SCM’s in VS Code, and use them side by side. Source control is accessible from the Source Control view:
All of this functionality is available directly from the VS Code UI:
VS Code will also recognize changes made outside the editor and behave appropriately.
Committing your recent changes within VS Code is a fairly straightforward process. Modified files are shown in the Source Control view with an M marker, while new untracked files are marked with a U. Stage your changes by hovering over the file and then clicking the plus sign (+). Add a commit message at the top of the view, and then click the check mark to commit the changes:
You can push local commits to GitHub from within VS Code as well. Select Sync from the Source Control view menu, or click Synchronize Changes on the status bar next to the branch indicator.
Conclusion
Visual Studio Code is one of the coolest general purpose editors and a great candidate for Python development. In this article, you learned:
Visual Studio Code has become my default editor for Python and other tasks, and I hope you give it a chance to become yours as well.
If you have questions or comments, please reach out in the comments below. There is also a lot more information at the Visual Studio Code website than we could cover here.
The author sends thanks to Dan Taylor from the Visual Studio Code team at Microsoft for his time and invaluable input in this article.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Development in Visual Studio Code (Setup Guide)
Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
About Jon Fincher
Jon taught Python and Java in two high schools in Washington State. Previously, he was a Program Manager at Microsoft.
Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:
Master Real-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
Master Real-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
Related Tutorial Categories: intermediate tools
Flask Tutorial in Visual Studio Code
Flask is a lightweight Python framework for web applications that provides the basics for URL routing and page rendering.
Flask is called a «micro» framework because it doesn’t directly provide features like form validation, database abstraction, authentication, and so on. Such features are instead provided by special Python packages called Flask extensions. The extensions integrate seamlessly with Flask so that they appear as if they were part of Flask itself. For example, Flask doesn’t provide a page template engine, but installing Flask includes the Jinja templating engine by default. For convenience, we typically speak of these defaults as part of Flask.
In this Flask tutorial, you create a simple Flask app with three pages that use a common base template. Along the way, you experience a number of features of Visual Studio Code including using the terminal, the editor, the debugger, code snippets, and more.
The completed code project for this Flask tutorial can be found on GitHub: python-sample-vscode-flask-tutorial.
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 Flask tutorial, you must do the following (which are the same steps as in the general Python tutorial):
Install a version of Python 3 (for which this tutorial is written). Options include:
On Windows, make sure the location of your Python interpreter is included in your PATH environment variable. You can check the location by running path at the command prompt. If the Python interpreter’s folder isn’t included, open Windows Settings, search for «environment», select Edit environment variables for your account, then edit the Path variable to include that folder.
Create a project environment for the Flask tutorial
In this section, you create a virtual environment in which Flask is installed. Using a virtual environment avoids installing Flask into a global Python environment and gives you exact control over the libraries used in an application. A virtual environment also makes it easy to Create a requirements.txt file for the environment.
Note: Use a stock Python installation when running the above commands. If you use python.exe from an Anaconda installation, you see an error because the ensurepip module isn’t available, and the environment is left in an unfinished state.
In VS Code, open the Command Palette (View > Command Palette or ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) )). Then select the Python: Select Interpreter command:
Run Terminal: Create New Terminal ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) )) from the Command Palette, which creates a terminal and automatically activates the virtual environment by running its activation script.
Note: On Windows, if your default terminal type is PowerShell, you may see an error that it cannot run activate.ps1 because running scripts is disabled on the system. The error provides a link for information on how to allow scripts. Otherwise, use Terminal: Select Default Shell to set «Command Prompt» or «Git Bash» as your default instead.
The selected environment appears on the right side of the VS Code status bar, and notice the (‘.venv’: venv) indicator that tells you that you’re using a virtual environment:
Update pip in the virtual environment by running the following command in the VS Code Terminal:
Install Flask in the virtual environment by running the following command in the VS Code Terminal:
Create and run a minimal Flask app
Tip: You can use multiple decorators on the same function, one per line, depending on how many different routes you want to map to the same function.
Save the app.py file ( ⌘S (Windows, Linux Ctrl+S ) ).
To open your default browser to the rendered page, Ctrl+click the http://127.0.0.1:5000/ URL in the terminal.
Observe that when you visit a URL like /, a message appears in the debug terminal showing the HTTP request:
Stop the app by using Ctrl+C in the terminal.
Run the app in the debugger
Debugging gives you the opportunity to pause a running program on a particular line of code. When a program is paused, you can examine variables, run code in the Debug Console panel, and otherwise take advantage of the features described on Debugging. Running the debugger also automatically saves any modified files before the debugging session begins.
Before you begin: Make sure you’ve stopped the running app at the end of the last section by using Ctrl+C in the terminal. If you leave the app running in one terminal, it continues to own the port. As a result, when you run the app in the debugger using the same port, the original running app handles all the requests and you won’t see any activity in the app being debugged and the program won’t stop at breakpoints. In other words, if the debugger doesn’t seem to be working, make sure that no other instance of the app is still running.
Replace the contents of app.py with the following code, which adds a second route and function that you can step through in the debugger:
As described in the code comments, always filter arbitrary user-provided information to avoid various attacks on your app. In this case, the code filters the name argument to contain only letters, which avoids injection of control characters, HTML, and so forth. (When you use templates in the next section, Flask does automatic filtering and you won’t need this code.)
Set a breakpoint at the first line of code in the hello_there function ( now = datetime.now() ) by doing any one of the following:
The breakpoint appears as a red dot in the left margin:
Switch to Run view in VS Code (using the left-side activity bar or F5 ). You may see the message «To customize Run and Debug create a launch.json file». This means that you don’t yet have a launch.json file containing debug configurations. VS Code can create that for you if you click on the create a launch.json file link:
Select the link and VS Code will prompt for a debug configuration. Select Flask from the dropdown and VS Code will populate a new launch.json file with a Flask run configuration. The launch.json file contains a number of debugging configurations, each of which is a separate JSON object within the configuration array.
Note: Once launch.json is created, an Add Configuration button appears in the editor. That button displays a list of additional configurations to add to the beginning of the configuration list. (The Run > Add Configuration menu command does the same action.).
Save launch.json ( ⌘S (Windows, Linux Ctrl+S ) ). In the debug configuration dropdown list select the Python: Flask configuration.
Start the debugger by selecting the Run > Start Debugging menu command, or selecting the green Start Debugging arrow next to the list ( F5 ):
Observe that the status bar changes color to indicate debugging:
A debugging toolbar (shown below) also appears in VS Code containing commands in the following order: Pause (or 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 ) ). See VS Code debugging for a description of each command.
Use Step Over to run the now = datetime.now() statement.
Tip: The Debug Console also shows exceptions from within the app that may not appear in the terminal. For example, if you see a «Paused on exception» message in the Call Stack area of Run and Debug view, switch to the Debug Console to see the exception message.
Copy that line into the > prompt at the bottom of the debug console, and try changing the formatting:
Step through a few more lines of code, if you’d like, then select Continue ( F5 ) to let the program run. The browser window shows the result:
Close the browser and stop the debugger when you’re finished. To stop the debugger, use the Stop toolbar button (the red square) or the Run > Stop Debugging command ( ⇧F5 (Windows, Linux Shift+F5 ) ).
Go to Definition and Peek Definition commands
During your work with Flask or any other library, you may want to examine the code in those libraries themselves. VS Code provides two convenient commands that navigate directly to the definitions of classes and other objects in any code:
Use a template to render a page
The app you’ve created so far in this tutorial generates only plain text web pages from Python code. Although it’s possible to generate HTML directly in code, developers avoid such a practice because it opens the app to cross-site scripting (XSS) attacks. In the hello_there function of this tutorial, for example, one might think to format the output in code with something like content = «
Hello there, » + clean_name + «!
A much better practice is to keep HTML out of your code entirely by using templates, so that your code is concerned only with data values and not with rendering.
In this section, you create a single page using a template. In the sections that follow, you configure the app to serve static files, and then create multiple pages to the app that each contains a nav bar from a base template.
You can see that the code is now much simpler, and concerned only with data values, because the markup and formatting is all contained in the template.
Start the program (inside or outside of the debugger, using ⌃F5 (Windows, Linux Ctrl+F5 ) ), navigate to a /hello/name URL, and observe the results.
Serve static files
Static files are of two types. First are those files like stylesheets to which a page template can just refer directly. Such files can live in any folder in the app, but are commonly placed within a static folder.
The following sections demonstrate both types of static files.
Refer to static files in a template
Within the static folder, create a file named site.css with the following contents. After entering this code, also observe the syntax highlighting that VS Code provides for CSS files, including a color preview:
Flask’s url_for tag that is used here, creates the appropriate path to the file. Because it can accept variables as arguments, url_for allows you to programmatically control the generated path, if desired.
Run the app, navigate to a /hello/name URL, and observe that the message renders in blue. Stop the app when you’re done.
Serve a static file from code
In the static folder, create a JSON data file named data.json with the following contents (which are meaningless sample data):
Run the app and navigate to the /api/data endpoint to see that the static file is returned. Stop the app when you’re done.
Create multiple templates that extend a base template
Because most web apps have more than one page, and because those pages typically share many common elements, developers separate those common elements into a base page template that other page templates can then extend. (This is also called template inheritance.)
Also, because you’ll likely create many pages that extend the same template, it’s helpful to create a code snippet in VS Code with which you can quickly initialize new page templates. A snippet helps you avoid tedious and error-prone copy-paste operations.
The following sections walk through different parts of this process.
Create a base page template and styles
A base page template in Flask contains all the shared parts of a set of pages, including references to CSS files, script files, and so forth. Base templates also define one or more block tags that other templates that extend the base are expected to override. A block tag is delineated by <% block %>and <% endblock %>in both the base template and extended templates.
The following steps demonstrate creating a base template.
In the templates folder, create a file named layout.html with the contents below, which contains blocks named «title» and «content». As you can see, the markup defines a simple nav bar structure with links to Home, About, and Contact pages, which you create in a later section. Each link again uses Flask’s url_for tag to generate a link at runtime for the matching route.
Add the following styles to static/site.css below the existing «message» style, and save the file. (This walkthrough doesn’t attempt to demonstrate responsive design; these styles simply generate a reasonably interesting result.)
You can run the app at this point, but because you haven’t made use of the base template anywhere and haven’t changed any code files, the result is the same as the previous step. Complete the remaining sections to see the final effect.
Create a code snippet
In VS Code, select the File (Windows/Linux) or Code (macOS), menu, then select Preferences > User snippets.
In the list that appears, select html. (The option may appear as «html.json» in the Existing Snippets section of the list if you’ve created snippets previously.)
Save the html.json file ( ⌘S (Windows, Linux Ctrl+S ) ).
For more information on code snippets in general, refer to Creating snippets.
Use the code snippet to add pages
With the code snippet in place, you can quickly create templates for the Home, About, and Contact pages.
When you select the completion, the snippet’s code appears with the cursor on the snippet’s insertion point:
Home page for the Visual Studio Code Flask tutorial.
, then save the file. These lines are the only unique parts of the extended page template:
About page for the Visual Studio Code Flask tutorial.
in the «title» and «content» blocks, respectively, then save the file.
Repeat the previous step to create templates/contact.html using Contact us and
Contact page for the Visual Studio Code Flask tutorial.
in the two content blocks.
Run the app
Note: If you’re not seeing the latest changes, you might need to do a hard refresh on the page to avoid seeing a cached file.
Optional activities
The following sections describe additional steps that you might find helpful in your work with Python and Visual Studio Code.
Create a requirements.txt file for the environment
When you share your app code through source control or some other means, it doesn’t make sense to copy all the files in a virtual environment because recipients can always recreate the environment themselves.
Accordingly, developers typically omit the virtual environment folder from source control and instead describe the app’s dependencies using a requirements.txt file.
Although you can create the file by hand, you can also use the pip freeze command to generate the file based on the exact libraries installed in the activated environment:
With your chosen environment selected using the Python: Select Interpreter command, run the Terminal: Create New Terminal command ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) )) to open a terminal with that environment activated.
In the terminal, run pip freeze > requirements.txt to create the requirements.txt file in your project folder.
Note: pip freeze lists all the Python packages you have installed in the current environment, including packages you aren’t currently using. The command also lists packages with exact version numbers, which you might want to convert to ranges for more flexibility in the future. For more information, see Requirements Files in the pip command documentation.
Refactor the project to support further development
Throughout this Flask tutorial, all the app code is contained in a single app.py file. To allow for further development and to separate concerns, it’s helpful to refactor the pieces of app.py into separate files.
In the hello_app folder, create a file named views.py that contains the routings and the view functions:
Optional: Right-click in the editor and select the Sort Imports command, which consolidates imports from identical modules, removes unused imports, and sorts your import statements. Using the command on the code above in views.py changes the imports as follows (you can remove the extra lines, of course):
In the hello_app folder, create a file __init__.py with the following contents:
In the hello_app folder, create a file webapp.py with the following contents:
Open the debug configuration file launch.json and update the env property as follows to point to the startup object:
Delete the original app.py file in the project root, as its contents have been moved into other app files.
Your project’s structure should now be similar to the following:
Run the app in the debugger again to make sure everything works. To run the app outside of the VS Code debugger, use the following steps from a terminal:
Create a container for a Flask app using the Docker extension
The Docker extension makes it easy to build, manage, and deploy containerized applications from Visual Studio Code. If you’re interested in learning how to create a Python container for the Flask app developed in this tutorial, check out the Python in a container tutorial, which will walk you through how to:
If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.
Next steps
Congratulations on completing this walkthrough of working with Flask in Visual Studio Code!
The completed code project from this tutorial can be found on GitHub: python-sample-vscode-flask-tutorial.
Because this tutorial has only scratched the surface of page templates, refer to the Jinja2 documentation for more information about templates. The Template Designer Documentation contains all the details on the template language. You might also want to review the official Flask tutorial as well as the documentation for Flask extensions.
To try your app on a production website, check out the tutorial Deploy Python apps to Azure App Service using Docker Containers. Azure also offers a standard container, App Service on Linux, to which you deploy web apps from within VS Code.
You may also want to review the following articles in the VS Code docs that are relevant to Python:
If you encountered any problems in the course of this tutorial, feel free to file an issue in the VS Code documentation repository.
Django Tutorial in Visual Studio Code
Django is a high-level Python framework designed for rapid, secure, and scalable web development. Django includes rich support for URL routing, page templates, and working with data.
In this Django tutorial, you create a simple Django app with three pages that use a common base template. You create this app in the context of Visual Studio Code in order to understand how to work with Django in the VS Code terminal, editor, and debugger. This tutorial does not explore various details about Django itself, such as working with data models and creating an administrative interface. For guidance on those aspects, refer to the Django documentation links at the end of this tutorial.
The completed code project from this Django tutorial can be found on GitHub: python-sample-vscode-django-tutorial.
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 Django tutorial, you must do the following (which are the same steps as in the general Python tutorial):
Install a version of Python 3 (for which this tutorial is written). Options include:
On Windows, make sure the location of your Python interpreter is included in your PATH environment variable. You can check the location by running path at the command prompt. If the Python interpreter’s folder isn’t included, open Windows Settings, search for «environment», select Edit environment variables for your account, then edit the Path variable to include that folder.
Create a project environment for the Django tutorial
In this section, you create a virtual environment in which Django is installed. Using a virtual environment avoids installing Django into a global Python environment and gives you exact control over the libraries used in an application. A virtual environment also makes it easy to Create a requirements.txt file for the environment.
Note: Use a stock Python installation when running the above commands. If you use python.exe from an Anaconda installation, you see an error because the ensurepip module isn’t available, and the environment is left in an unfinished state.
In VS Code, open the Command Palette (View > Command Palette or ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) )). Then select the Python: Select Interpreter command:
Run Terminal: Create New Terminal ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) ) from the Command Palette, which creates a terminal and automatically activates the virtual environment by running its activation script.
Note: On Windows, if your default terminal type is PowerShell, you may see an error that it cannot run activate.ps1 because running scripts is disabled on the system. The error provides a link for information on how to allow scripts. Otherwise, use Terminal: Select Default Shell to set «Command Prompt» or «Git Bash» as your default instead.
The selected environment appears on the right side of the VS Code status bar, and notices the (‘.venv’: venv) indicator that tells you that you’re using a virtual environment:
Update pip in the virtual environment by running the following command in the VS Code Terminal:
Install Django in the virtual environment by running the following command in the VS Code Terminal:
Create and run a minimal Django app
In Django terminology, a «Django project» is composed of several site-level configuration files, along with one or more «apps» that you deploy to a web host to create a full web application. A Django project can contain multiple apps, each of which typically has an independent function in the project, and the same app can be in multiple Django projects. An app, for its part, is just a Python package that follows certain conventions that Django expects.
Create the Django project
In the VS Code Terminal where your virtual environment is activated, run the following command:
Create an empty development database by running the following command:
When you run the server the first time, it creates a default SQLite database in the file db.sqlite3 that is intended for development purposes, but can be used in production for low-volume web apps. For additional information about databases, see the Types of databases section.
Django’s built-in web server is intended only for local development purposes. When you deploy to a web host, however, Django uses the host’s web server instead. The wsgi.py and asgi.py modules in the Django project take care of hooking into the production servers.
Ctrl+click the http://127.0.0.1:8000/ URL in the terminal output window to open your default browser to that address. If Django is installed correctly and the project is valid, you see the default page shown below. The VS Code terminal output window also shows the server log.
When you’re done, close the browser window and stop the server in VS Code using Ctrl+C as indicated in the terminal output window.
Create a Django app
In the VS Code Terminal with your virtual environment activated, run the administrative utility’s startapp command in your project folder (where manage.py resides):
The command creates a folder called hello that contains a number of code files and one subfolder. Of these, you frequently work with views.py (that contains the functions that define pages in your web app) and models.py (that contains classes defining your data objects). The migrations folder is used by Django’s administrative utility to manage database versions as discussed later in this tutorial. There are also the files apps.py (app configuration), admin.py (for creating an administrative interface), and tests.py (for creating tests), which are not covered here.
Modify hello/views.py to match the following code, which creates a single view for the app’s home page:
Save all modified files.
In the VS Code Terminal, again with the virtual environment activated, run the development server with python manage.py runserver and open a browser to http://127.0.0.1:8000/ to see a page that renders «Hello, Django».
Create a debugger launch profile
You’re probably already wondering if there’s an easier way to run the server and test the app without typing python manage.py runserver each time. Fortunately, there is! You can create a customized launch profile in VS Code, which is also used for the inevitable exercise of debugging.
Switch to Run view in VS Code (using the left-side activity bar or F5 ). You may see the message «To customize Run and Debug create a launch.json file». This means that you don’t yet have a launch.json file containing debug configurations. VS Code can create that for you if you click on the create a launch.json file link:
Select the link and VS Code will prompt for a debug configuration. Select Django from the dropdown and VS Code will populate a new launch.json file with a Django run configuration. The launch.json file contains a number of debugging configurations, each of which is a separate JSON object within the configuration array.
Scroll down to and examine the configuration with the name «Python: Django»:
This configuration tells VS Code to run «$
Test the configuration by selecting the Run > Start Debugging menu command, or selecting the green Start Debugging arrow next to the list ( F5 ):
Ctrl+click the http://127.0.0.1:8000/ URL in the terminal output window to open the browser and see that the app is running properly.
Close the browser and stop the debugger when you’re finished. To stop the debugger, use the Stop toolbar button (the red square) or the Run > Stop Debugging command ( ⇧F5 (Windows, Linux Shift+F5 ) ).
You can now use the Run > Start Debugging at any time to test the app, which also has the benefit of automatically saving all modified files.
Explore the debugger
Debugging gives you the opportunity to pause a running program on a particular line of code. When a program is paused, you can examine variables, run code in the Debug Console panel, and otherwise take advantage of the features described on Debugging. Running the debugger also automatically saves any modified files before the debugging session begins.
Before you begin: Make sure you’ve stopped the running app at the end of the last section by using Ctrl+C in the terminal. If you leave the app running in one terminal, it continues to own the port. As a result, when you run the app in the debugger using the same port, the original running app handles all the requests and you won’t see any activity in the app being debugged and the program won’t stop at breakpoints. In other words, if the debugger doesn’t seem to be working, make sure that no other instance of the app is still running.
Replace the contents of views.py with the following code to define the hello_there function that you can step through in the debugger:
The name variable defined in the URL route is given as an argument to the hello_there function. As described in the code comments, always filter arbitrary user-provided information to avoid various attacks on your app. In this case, the code filters the name argument to contain only letters, which avoids injection of control characters, HTML, and so forth. (When you use templates in the next section, Django does automatic filtering and you don’t need this code.)
Set a breakpoint at the first line of code in the hello_there function ( now = datetime.now() ) by doing any one of the following:
The breakpoint appears as a red dot in the left margin:
Start the debugger by selecting the Run > Start Debugging menu command, or selecting the green Start Debugging arrow next to the list ( F5 ):
Observe that the status bar changes color to indicate debugging:
A debugging toolbar (shown below) also appears in VS Code containing commands in the following order: Pause (or 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 ) ). See VS Code debugging for a description of each command.
Use Step Over to run the now = datetime.now() statement.
Tip: The Debug Console also shows exceptions from within the app that may not appear in the terminal. For example, if you see a «Paused on exception» message in the Call Stack area of Run and Debug view, switch to the Debug Console to see the exception message.
Copy that line into the > prompt at the bottom of the debug console, and try changing the formatting:
Step through a few more lines of code, if you’d like, then select Continue ( F5 ) to let the program run. The browser window shows the result:
Close the browser and stop the debugger when you’re finished. To stop the debugger, use the Stop toolbar button (the red square) or the Run > Stop Debugging command ( ⇧F5 (Windows, Linux Shift+F5 ) ).
Go to Definition and Peek Definition commands
During your work with Django or any other library, you may want to examine the code in those libraries themselves. VS Code provides two convenient commands that navigate directly to the definitions of classes and other objects in any code:
Use a template to render a page
The app you’ve created so far in this tutorial generates only plain text web pages from Python code. Although it’s possible to generate HTML directly in code, developers avoid such a practice because it opens the app to cross-site scripting (XSS) attacks. In the hello_there function of this tutorial, for example, one might think to format the output in code with something like content = «
Hello there, » + clean_name + «!
A much better practice is to keep HTML out of your code entirely by using templates, so that your code is concerned only with data values and not with rendering.
In Django, a template is an HTML file that contains placeholders for values that the code provides at run time. The Django templating engine then takes care of making the substitutions when rendering the page, and provides automatic escaping to prevent XSS attacks (that is, if you tried using HTML in a data value, you would see the HTML rendered only as plain text). The code, therefore, concerns itself only with data values and the template concerns itself only with markup. Django templates provide flexible options such as template inheritance, which allows you to define a base page with common markup and then build upon that base with page-specific additions.
In this section, you start by creating a single page using a template. In subsequent sections, you configure the app to serve static files and then create multiple pages to the app that each contains a nav bar from a base template. Django templates also support control flow and iteration, as you see later in this tutorial in the context of template debugging.
In the web_project/settings.py file, locate the INSTALLED_APPS list and add the following entry, which makes sure the project knows about the app so it can handle templating:
You can see that the code is now much simpler, and concerned only with data values, because the markup and formatting is all contained in the template.
Start the program (inside or outside of the debugger, using ⌃F5 (Windows, Linux Ctrl+F5 ) ), navigate to a /hello/name URL, and observe the results.
Serve static files
Serving static files in Django is something of an art, especially when deploying to production. What’s shown here is a simple approach that works with the Django development server and also a production server like Gunicorn. A full treatment of static files, however, is beyond the scope of this tutorial, so for more information, see Managing static files in the Django documentation.
Ready the app for static files
In that same file, add the following line at the end, which includes standard static file URLs to the list that the project recognizes:
Refer to static files in a template
The reason for this extra subfolder is that when you deploy the Django project to a production server, you collect all the static files into a single folder that’s then served by a dedicated static file server. The static/hello subfolder ensures that when the app’s static files are collected, they’re in an app-specific subfolder and won’t collide with file from other apps in the same project.
In the static/hello folder, create a file named site.css with the following contents. After entering this code, also observe the syntax highlighting that VS Code provides for CSS files, including a color preview.
Run the app, navigate to a /hello/name URL, and observe that the message renders in blue. Stop the app when you’re done.
Use the collectstatic command
For production deployments, you typically collect all the static files from your apps into a single folder using the python manage.py collectstatic command. You can then use a dedicated static file server to serve those files, which typically results in better overall performance. The following steps show how this collection is made, although you don’t use the collection when running with the Django development server.
In practice, run collectstatic any time you change static files and before deploying into production.
Create multiple templates that extend a base template
Because most web apps have more than one page, and because those pages typically share many common elements, developers separate those common elements into a base page template that other page templates then extend. (This is also called template inheritance, meaning the extended pages inherit elements from the base page.)
Also, because you’ll likely create many pages that extend the same template, it’s helpful to create a code snippet in VS Code with which you can quickly initialize new page templates. A snippet helps you avoid tedious and error-prone copy-paste operations.
The following sections walk through different parts of this process.
Create a base page template and styles
A base page template in Django contains all the shared parts of a set of pages, including references to CSS files, script files, and so forth. Base templates also define one or more block tags with content that extended templates are expected to override. A block tag is delineated by <% block %>and <% endblock %>in both the base template and extended templates.
The following steps demonstrate creating a base template.
In the templates/hello folder, create a file named layout.html with the contents below, which contains blocks named «title» and «content». As you can see, the markup defines a simple nav bar structure with links to Home, About, and Contact pages, which you create in a later section. Notice the use of Django’s <% url %>tag to refer to other pages through the names of the corresponding URL patterns rather than by relative path.
Add the following styles to static/hello/site.css below the existing «message» style, and save the file. (This walkthrough doesn’t attempt to demonstrate responsive design; these styles simply generate a reasonably interesting result.)
You can run the app at this point, but because you haven’t made use of the base template anywhere and haven’t changed any code files, the result is the same as the previous step. Complete the remaining sections to see the final effect.
Create a code snippet
In VS Code, select the File (Windows/Linux) or Code (macOS), menu, then select Preferences > User snippets.
In the list that appears, select html. (The option may appear as «html.json» in the Existing Snippets section of the list if you’ve created snippets previously.)
Save the html.json file ( ⌘S (Windows, Linux Ctrl+S ) ).
For more information on code snippets in general, refer to Creating snippets.
Use the code snippet to add pages
With the code snippet in place, you can quickly create templates for the Home, About, and Contact pages.
When you select the completion, the snippet’s code appears with the cursor on the snippet’s insertion point:
Home page for the Visual Studio Code Django tutorial.
, then save the file. These lines are the only unique parts of the extended page template:
About page for the Visual Studio Code Django tutorial.
in the «title» and «content» blocks, respectively, then save the file.
Repeat the previous step to create templates/hello/contact.html using Contact us and
Contact page for the Visual Studio Code Django tutorial.
Run the app
Work with data, data models, and migrations
With Django, you work with your database almost exclusively through the models you define in code. Django’s «migrations» then handle all the details of the underlying database automatically as you evolve the models over time. The general workflow is as follows:
In code, too, you work exclusively with your model classes to store and retrieve data; Django handles the underlying details. The one exception is that you can write data into your database using the Django administrative utility loaddata command. This utility is often used to initialize a data set after the migrate command has initialized the schema.
Types of databases
By default, Django includes a db.sqlite3 file for an app’s database that’s suitable for development work. As described on When to use SQLite (sqlite.org), SQLite works fine for low to medium traffic sites with fewer than 100 K hits/day, but is not recommended for higher volumes. It’s also limited to a single computer, so it cannot be used in any multi-server scenario such as load-balancing and geo-replication.
For these reasons, consider using a production-level data store such as PostgreSQL, MySQL, and SQL Server. For information on Django’s support for other databases, see Database setup. You can also use the Azure SDK for Python to work with Azure storage services like tables and blobs.
Define models
For example, add the following class in models.py to define a data model that represents dated entries in a simple message log:
A model class can include methods that return values computed from other class properties. Models typically include a __str__ method that returns a string representation of the instance.
Migrate the database
Take a look in the migrations folder to see the scripts that makemigrations generates. You can also look at the database itself to see that the schema is updated.
If you see errors when running the commands, make sure you’re not using a debugging terminal that’s left over from previous steps, as they may not have the virtual environment activated.
Use the database through the models
With your models in place and the database migrated, you can store and retrieve data using only your models. In this section, you add a form page to the app through which you can log a message. You then modify the home page to display those messages. Because you modify many code files here, be mindful of the details.
In the hello folder (where you have views.py ), create a new file named forms.py with the following code, which defines a Django form that contains a field drawn from the data model, LogMessage :
In the templates/hello folder, create a new template named log_message.html with the following contents, which assumes that the template is given a variable named form to define the body of the form. It then adds a submit button with the label «Log».
Note: Django’s <% csrf_token %>tag provides protection from cross-site request forgeries. See Cross Site Request Forgery protection in the Django documentation for details.
In the app’s static/hello/site.css file, add a rule to make the input form wider:
In the app’s urls.py file, add a route for the new page:
Run the app and open a browser to the home page. Select the Log Message link on the nav bar, which should display the message logging page:
Enter a message, select Log, and you should be taken back to the home page. The home page doesn’t yet show any of the logged messages yet (which you remedy in a moment). Feel free to log a few more messages as well. If you want, peek in the database using a tool like SQLite Browser to see that records have been created. Open the database as read-only, or otherwise remember to close the database before using the app, otherwise the app will fail because the database is locked.
Stop the app when you’re done.
Start the app and open a browser to the home page, which should now display messages:
Stop the app when you’re done.
Use the debugger with page templates
As shown in the previous section, page templates can contain procedural directives like <% for message in message_list %>and <% if message_list %>, rather than only passive, declarative elements like <% url %>and <% block %>. As a result, you can have programming errors inside templates as with any other procedural code.
Fortunately, the Python Extension for VS Code provides template debugging when you have «django»: true in the debugging configuration (as you do already). The following steps demonstrate this capability:
Run the app in the debugger and open a browser to the home page. (If you’re already running the debugger, you don’t have to restart the app after setting breakpoints; just refresh the page.) Observe that VS Code breaks into the debugger in the template on the <% if %>statement and shows all the context variables in the Variables pane:
When you’re ready, select Continue ( F5 ) to finish running the app and view the rendered page in the browser. Stop the debugger when you’re done.
Optional activities
The following sections describe additional steps that you might find helpful in your work with Python and Visual Studio Code.
Create a requirements.txt file for the environment
When you share your app code through source control or some other means, it doesn’t make sense to copy all the files in a virtual environment because recipients can always recreate that environment themselves.
Accordingly, developers typically omit the virtual environment folder from source control and instead describe the app’s dependencies using a requirements.txt file.
Although you can create the file by hand, you can also use the pip freeze command to generate the file based on the exact libraries installed in the activated environment:
With your chosen environment selected using the Python: Select Interpreter command, run the Terminal: Create New Terminal command ( ⌃⇧` (Windows, Linux Ctrl+Shift+` ) )) to open a terminal with that environment activated.
In the terminal, run pip freeze > requirements.txt to create the requirements.txt file in your project folder.
Note: pip freeze lists all the Python packages you have installed in the current environment, including packages you aren’t currently using. The command also lists packages with exact version numbers, which you might want to convert to ranges for more flexibility in the future. For more information, see Requirements Files in the pip command documentation.
Create a superuser and enable the administrative interface
By default, Django provides an administrative interface for a web app that’s protected by authentication. The interface is implemented through the built-in django.contrib.admin app, which is included by default in the project’s INSTALLED_APPS list ( settings.py ), and authentication is handled with the built-in django.contrib.auth app, which is also in INSTALLED_APPS by default.
Perform the following steps to enable the administrative interface:
Be sure to remember your username and password combination. These are the credentials you use to authenticate with the app.
Add the following URL route in the project-level urls.py ( web_project/urls.py in this tutorial) to point to the built-in administrative interface:
Run the server, then open a browser to the app’s /admin page (such as http://127.0.0.1:8000/admin when using the development server).
Once you’re authenticated, you see the default administration page, through which you can manage users and groups:
You can customize the administrative interface as much as you like. For example, you could provide capabilities to edit and remove entries in the database. For more information on making customizations, refer to the Django admin site documentation.
Create a container for a Django app using the Docker extension
The Docker extension makes it easy to build, manage, and deploy containerized applications from Visual Studio Code. If you’re interested in learning how to create a Python container for the Django app developed in this tutorial, check out the Python in a container tutorial, which will walk you through how to:
Next steps
Congratulations on completing this walkthrough of working with Django in Visual Studio Code!
The completed code project from this tutorial can be found on GitHub: python-sample-vscode-django-tutorial.
In this tutorial, we’ve only scratched the surface of everything Django can do. Be sure to visit the Django documentation and the official Django tutorial for many more details on views, templates, data models, URL routing, the administrative interface, using other kinds of databases, deployment to production, and more.
To try your app on a production website, check out the tutorial Deploy Python apps to Azure App Service using Docker Containers. Azure also offers a standard container, App Service on Linux, to which you deploy web apps from within VS Code.
You may also want to review the following articles in the VS Code docs that are relevant to Python:
If you encountered any problems in the course of this tutorial, feel free to file an issue in the VS Code documentation repository.
Установка поддержки Python в Visual Studio
Поддержка Python сейчас доступна только в Visual Studio для Windows. В Mac и Linux поддержка Python доступна через Visual Studio Code.
Скачайте и запустите последнюю версию Visual Studio Installer для Windows. Поддержка Python доступна в выпуске 15.2 и выше. Если вы уже установили Visual Studio, откройте этот продукт и запустите установщик, выбрав Сервис>Получить средства и компоненты.
Выпуск Community предназначен для индивидуальных разработчиков, использования при аудиторном обучении и в научных исследованиях, а также разработки решений с открытым кодом. Если программу планируется использовать в других целях, установите Visual Studio Professional или Visual Studio Enterprise.
Установщик предоставляет список рабочих нагрузок, которые представляют собой группы связанных параметров для конкретных областей разработки. Для Python выберите рабочую нагрузку Разработка на Python и нажмите Установить.
Python testing in Visual Studio Code
The Python extension supports testing with Python’s built-in unittest framework and pytest.
A little background on unit testing
(If you’re already familiar with unit testing, you can skip to the walkthroughs.)
A unit is a specific piece of code to be tested, such as a function or a class. Unit tests are then other pieces of code that specifically exercise the code unit with a full range of different inputs, including boundary and edge cases.
For example, say you have a function to validate the format of an account number that a user enters in a web form:
Unit tests are concerned only with the unit’s interface—its arguments and return values—not with its implementation (which is why no code is shown here in the function body; often you’d be using other well-tested libraries to help implement the function). In this example, the function accepts any string and returns true if that string contains a properly formatted account number, false otherwise.
To thoroughly test this function, you want to throw at it every conceivable input: valid strings, mistyped strings (off by one or two characters, or containing invalid characters), strings that are too short or too long, blank strings, null arguments, strings containing control characters (non-text codes), string containing HTML, strings containing injection attacks (such as SQL commands or JavaScript code), and so on. It’s especially important to test security cases like injection attacks if the validated string is later used in database queries or displayed in the app’s UI.
For each input, you then define the function’s expected return value (or values). In this example, again, the function should return true for only properly formatted strings. (Whether the number itself is a real account is a different matter that would be handled elsewhere through a database query.)
With all the arguments and expected return values in hand, you now write the tests themselves, which are pieces of code that call the function with a particular input, then compare the actual return value with the expected return value (this comparison is called an assertion):
The exact structure of the code depends on the test framework you’re using, and specific examples are provided later in this article. In any case, as you can see, each test is simple: invoke the function with an argument and assert the expected return value.
The combined results of all the tests is your test report, which tells you whether the function (the unit), is behaving as expected across all test cases. That is, when a unit passes all of its tests, you can be confident that it’s functioning properly. (The practice of test-driven development is where you actually write the tests first, then write the code to pass increasingly more tests until all of them pass.)
Because unit tests are small, isolated pieces of code (in unit testing you avoid external dependencies and use mock data or otherwise simulated inputs), they’re quick and inexpensive to run. This characteristic means that you can run unit tests early and often. Developers typically run unit tests even before committing code to a repository; gated check-in systems can also run unit tests before merging a commit. Many continuous integration systems also run unit tests after every build. Running the unit test early and often means that you quickly catch regressions, which are unexpected changes in the behavior of code that previously passed all its unit tests. Because the test failure can easily be traced to a particular code change, it’s easy to find and remedy the cause of the failure, which is undoubtedly better than discovering a problem much later in the process!
For a general background on unit testing, read Unit testing on Wikipedia. For useful unit test examples, you can review https://github.com/gwtw/py-sorting, a repository with tests for different sorting algorithms.
Example test walkthroughs
Python tests are Python classes that reside in separate files from the code being tested. Each test framework specifies the structure and naming of tests and test files. Once you write tests and enable a test framework, VS Code locates those tests and provides you with various commands to run and debug them.
For this section, create a folder and open it in VS Code. Then create a file named inc_dec.py with the following code to be tested:
With this code, you can experience working with tests in VS Code as described in the sections that follow.
Configure tests
Once you have the Python extension installed and a Python file open within the editor, a test beaker icon will be displayed on the VS Code Activity bar. The beaker icon is for the Test Explorer view. When opening the Test Explorer, you will see a Configure Tests button if you don’t have a test framework enabled. Once you select Configure Tests, you will be prompted to select a test framework and a folder containing the tests. If you’re using unittest, you will also be asked to select the file glob pattern used to identify your test files.
You can configure your tests anytime by using the Python: Configure Tests command from the Command Palette. You can also configure testing manually by setting either python.testing.unittestEnabled or python.testing.pytestEnabled to true. Each framework also has specific configuration settings as described under Test configuration settings for their folders and patterns.
When you enable a test framework, VS Code prompts you to install the framework package if it’s not already present in the currently activated environment:
Create tests
Each test framework has its own conventions for naming test files and structuring the tests within, as described in the following sections. Each case includes two test methods, one of which is intentionally set to fail for the purposes of demonstration.
Tests in unittest
Create a file named test_unittest.py that contains a test class with two test methods:
Tests in pytest
Create a file named test_pytest.py that contains two test methods:
Test discovery
By default, the Python extension attempts to discover tests once you enable a framework. You can trigger test discovery at any time using the Test: Refresh Tests command.
Test discovery applies the discovery patterns for the current framework (which can be customized using the Test configuration settings). The default behavior is as follows:
Tip: Sometimes tests placed in subfolders aren’t discovered because such test files cannot be imported. To make them importable, create an empty file named __init__.py in that folder.
If the test discovery succeeds, you’ll see tests listed in the Test Explorer:
If discovery fails (for example, the test framework isn’t installed or you have a syntax error in your test file), you’ll see an error message displayed in the Test Explorer. You can check the Python output panel to see the entire error message (use the View > Output menu command to show the Output panel, then select Python from the dropdown on the right side).
Once VS Code recognizes tests, it provides several ways to run those tests as described in Run tests.
Run tests
You can run tests using any of the following actions:
With a test file open, select the green run icon that is displayed in the gutter next to the test definition line, as shown in the previous section. This command runs only that one method.
From the Command Palette, by running any of the following commands:
From the Test Explorer:
To run all discovered tests, select the play button at the top of Test Explorer:
To run a specific group of tests, or a single test, select the file, class, or test, then select the play button to the right of that item:
You can also run a selection of tests through the Test Explorer. To do that, Ctrl+Click (or Cmd+Click on macOS) on the tests you wish to run, right-click on one of them and then select Run Test.
In the Test Explorer, results are shown for individual tests and any classes and files containing those tests.
VS Code also shows test results in the Python Test Log output panel.
Run tests in parallel
Support for running tests in parallel with pytest is available through the pytest-xdist package. To enable parallel testing:
Open the integrated terminal and install the pytest-xdist package. For more details, refer to the project’s documentation page.
For Windows
For macOS/Linux
Next, create a file named pytest.ini in your project directory and add the content below, specifying the number of CPUs to be used. For example, to set it up for 4 CPUs:
Or, if you are using a pyproject.toml file
Run your tests, which will now be run in parallel.
Debug tests
You might occasionally need to step through and analyze tests in the debugger, either because the tests themselves have a code defect you need to track down or in order to better understand why an area of code being tested is failing.
For example, the test_decrement functions given earlier are failing because the assertion itself is faulty. The following steps demonstrate how to analyze the test:
Set a breakpoint on the first line in the test_decrement function.
Right-click on the gutter decoration next to the function definition and select Debug Test, or select the Debug Test icon next to that test in the Test Explorer. VS Code starts the debugger and pauses at the breakpoint.
In the Debug Console panel, enter inc_dec.decrement(3) to see that the actual result is 2, whereas the expected result specified in the test is the incorrect value of 4.
Stop the debugger and correct the faulty code:
Save the file and run the tests again to confirm that they pass, and see that the gutter decorations also indicate passing status.
Note: Running or debugging a test does not automatically save the test file. Always be sure to save changes to a test before running it, otherwise you’ll likely be confused by the results because they still reflect the previous version of the file!
You can use the following commands from the Command Palette to debug tests:
You can also change the default behavior of clicking on the gutter decoration to debug tests instead of run, by changing the testing.defaultGutterClickAction setting value to debug in your settings.json file.
For example, the configuration below in the launch.json file disables the justMyCode setting for debugging tests:
For more information on debugging, see Python debugging configurations and the general VS Code Debugging article.
Test commands
Below are all the supported commands for testing with the Python extension in VS Code:
Command Name | Description |
---|---|
Python: Configure Tests | Configure the test framework to be used with the Python extension. |
Test: Clear All Results | Clear all tests statuses, as the UI persists test results across sessions. |
Test: Debug Failed Tests | Debug tests that failed in the most recent test run. |
Test: Debug Last Run | Debug tests that were executed in the most recent test run. |
Test: Debug Test at Cursor | Debug the test method where you have your cursor focused on the editor. Similar to Python: Debug Test Method. on versions prior to 2021.9. |
Test: Debug Tests in Current File | Debug tests in the file that is currently in focus on the editor. |
Test: Go to Next Test Failure | If the error peek view is open, open and move to the peek view of the next test in the explorer that has failed. |
Test: Go to Previous Test Failure | If the error peek view is open, open and move to the peek view of the previous test in the explorer that has failed. |
Test: Peek Output | Opens the error peek view for a test method that has failed. |
Test: Refresh Tests | Perform test discovery and updates the Test Explorer to reflect any test changes, addition, or deletion. Similar to Python: Discover Tests on versions prior to 2021.9. |
Test: Rerun Failed Tests | Run tests that failed in the most recent test run. Similar to Python: Run Failed Tests on versions prior to 2021.9. |
Test: Rerun Last Run | Debug tests that were executed in the most recent test run. |
Test: Run All Tests | Run all discovered tests. Equivalent to Python: Run All Tests on versions prior to 2021.9. |
Test: Run Test at Cursor | Run the test method where you have your cursor focused on the editor. Similar to Python: Run Test Method. on versions prior to 2021.9. |
Test: Run Test in Current File | Run tests in the file that is currently in focus on the editor. Equivalent to Python: Run Current Test File on versions prior to 2021.9. |
Test: Show Output | Open the output with details of all the test runs. Similar to Python: Show Test Output on versions prior to 2021.9. |
Testing: Focus on Test Explorer View | Open the Test Explorer view. Similar to Testing: Focus on Python View on versions prior to 2021.9. |
Test: Stop Refreshing Tests | Cancel test discovery. |
Test configuration settings
The behavior of testing with Python is driven by general UI settings provided by VS Code, and settings that are specific to Python and to whichever framework you’ve enabled.
General UI settings
The settings that affect the UI of the testing features are provided by VS Code itself, and can be found in the VS Code Settings editor when you search for «Testing».
General Python settings
Setting (python.testing.) | Default | Description |
---|---|---|
autoTestDiscoverOnSaveEnabled | true | Specifies whether to enable or disable auto run test discovery when saving a test file. You may need to reload the window after making changes to this setting for it to be applied. |
cwd | null | Specifies an optional working directory for tests. |
debugPort | 3000 | Port number used for debugging of unittest tests. |
promptToConfigure | true | Specifies whether VS Code prompts to configure a test framework if potential tests are discovered. |
unittest configuration settings
Setting (python.testing.) | Default | Description |
---|---|---|
unittestEnabled | false | Specifies whether unittest is enabled as the test framework. The equivalent setting for pytest should be disabled. |
unittestArgs | [«-v», «-s», «.», «-p», «*test*.py»] | Arguments to pass to unittest, where each element that’s separated by a space is a separate item in the list. See below for a description of the defaults. |
The default arguments for unittest are as follows:
To stop a test run on the first failure, add the fail fast option «-f» to the arguments array.
See unittest command-line interface for the full set of available options.
pytest configuration settings
Setting (python.testing.) | Default | Description |
---|---|---|
pytestEnabled | false | Specifies whether pytest is enabled as the test framework. The equivalent setting for unittest should be disabled. |
pytestPath | «pytest» | Path to pytest. Use a full path if pytest is located outside the current environment. |
pytestArgs | [] | Arguments to pass to pytest, where each element that’s separated by a space is a separate item in the list. See pytest command-line options. |
You can also configure pytest using a pytest.ini file as described on pytest Configuration.
Linting Python in Visual Studio Code
Linting highlights syntactical and stylistic problems in your Python source code, which often helps you identify and correct subtle programming errors or unconventional coding practices that can lead to errors. For example, linting detects use of an uninitialized or undefined variable, calls to undefined functions, missing parentheses, and even more subtle issues such as attempting to redefine built-in types or functions. Linting is thus distinct from Formatting because linting analyzes how the code runs and detects errors whereas formatting only restructures how code appears.
Note: Stylistic and syntactical code detection is enabled by the Language Server. To enable third-party linters for additional problem detection, you can enable them by using the Python: Select Linter command and selecting the appropriate linter.
Enable linting
Enabling a linter prompts you to install the required packages in your selected environment for the chosen linter.
Note: If you’re using a global environment and VS Code is not running elevated, linter installation may fail. In that case, either run VS Code elevated, or manually run the Python package manager to install the linter at an elevated command prompt for the same environment: for example sudo pip3 install pylint (macOS/Linux) or pip install pylint (Windows, at an elevated prompt).
Disable linting
You can easily toggle between enabling and disabling your linter. To switch, open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ) and select the Python: Enable/Disable Linting command.
This will populate a dropdown with the current linting state and options to Enable or Disable Python linting.
Run linting
To perform linting, open the Command Palette ( ⇧⌘P (Windows, Linux Ctrl+Shift+P ) ), filter on «linting», and select Python: Run Linting. Linting will run automatically when you save a file.
Issues are shown in the Problems panel and as wavy underlines in the code editor. Hovering over an underlined issue displays the details:
General linting settings
You can add any of the linting settings to your user settings.json file (opened with the File > Preferences > Settings command ⌘, (Windows, Linux Ctrl+, ) ). Refer to User and Workspace settings to find out more about working with settings in VS Code.
To change the linting behavior across all enabled linters, modify the following settings:
Feature | Setting (python.linting.) | Default value |
---|---|---|
Linting in general | enabled | true |
Linting on file save | lintOnSave | true |
Maximum number of linting messages | maxNumberOfProblems | 100 |
Exclude file and folder patterns | ignorePatterns | [«.vscode/*.py», «**/site-packages/**/*.py»] |
Specific linters
The following table provides a summary of available Python linters and their basic settings. For descriptions of individual settings, see the Linter settings reference.
Linter | Package name for pip install command | True/false enable setting (python.linting.) | Arguments setting (python.linting.) | Custom path setting (python.linting.) |
---|---|---|---|---|
Pylint | pylint | pylintEnabled | pylintArgs | pylintPath |
Flake8 | flake8 | flake8Enabled | flake8Args | flake8Path |
mypy | mypy | mypyEnabled | mypyArgs | mypyPath |
pycodestyle (pep8) | pycodestyle | pycodestyleEnabled | pycodestyleArgs | pycodestylePath |
prospector | prospector | prospectorEnabled | prospectorArgs | prospectorPath |
pylama | pylama | pylamaEnabled | pylamaArgs | pylamaPath |
bandit | bandit | banditEnabled | banditArgs | banditPath |
To select a different linter, use the Python: Select Linter command. You can also edit your settings manually to enable multiple linters. Note, that using the Select Linter command overwrites those edits.
Custom arguments are specified in the appropriate arguments setting for each linter. Each top-level element of an argument string that’s separated by a space on the command line must be a separate item in the args list. For example:
If a top-level element is a single value (delineated by quotation marks or braces), it still appears as a single item in the list even if the value itself contains spaces.
A custom path is generally unnecessary as the Python extension resolves the path to the linter based on the Python interpreter being used (see Environments). To use a different version of a linter, specify its path in the appropriate custom path setting. For example, if your selected interpreter is a virtual environment but you want to use a linter that’s installed in a global environment, then set the appropriate path setting to point to the global environment’s linter.
Note: The following sections provide additional details for the individual linters linked in the Specific linters table above. In general, custom rules must be specified in a separate file as required by the linter you’re using.
Pylint
Pylint messages fall into the categories in the following table with the indicated mapping to VS Code categories. You can change the setting to change the mapping.
Pylint category | Description | VS Code category mapping | Applicable setting (python.linting.) |
---|---|---|---|
Convention (C) | Programming standard violation | Information (underline) | pylintCategorySeverity.convention |
Refactor (R) | Bad code smell | Hint (light bulbs) | pylintCategorySeverity.refactor |
Warning (W) | Python-specific problems | Warning | pylintCategorySeverity.warning |
Error (E) | Likely code bugs | Error (underline) | pylintCategorySeverity.error |
Fatal (F) | An error prevented further Pylint processing | Error | pylintCategorySeverity.fatal |
Command-line arguments and configuration files
You can easily generate an options file using different methods. See Pylint command-line arguments for general switches.
If you’re using command-line arguments:
Command-line arguments can be used to load Pylint plugins, such as the plugin for Django:
If you’re using a pylintrc file:
To control which Pylint messages are shown, add the following contents to an options file:
If you’re using Pylint:
You can create an options file using Pylint itself, by running the command below.
If you are running Pylint in PowerShell, you have to explicitly specify a UTF-8 output encoding. This file contains sections for all the Pylint options, along with documentation in the comments.
pydocstyle
Command-line arguments and configuration files
See pydocstyle Command Line Interface for general options. For example, to ignore error D400 (first line should end with a period), add the following line to your settings.json file:
A code prefix also instructs pydocstyle to ignore specific categories of errors. For example, to ignore all Docstring Content issues (D4XXX errors), add the following line to settings.json :
More details can be found in the pydocstyle documentation.
Options can also be read from a [pydocstyle] section of any of the following configuration files:
For more information, see Configuration Files.
Message category mapping
The Python extension maps all pydocstyle errors to the Convention (C) category.
pycodestyle (pep8)
Command-line arguments and configuration files
See pycodestyle example usage and output for general switches. For example, to ignore error E303 (too many blank lines), add the following line to your settings.json file:
pycodestyle options are read from the [pycodestyle] section of a tox.ini or setup.cfg file located in any parent folder of the path(s) being processed. For details, see pycodestyle configuration.
Message category mapping
The Python extension maps pycodestyle message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.
pycodestyle category | Applicable setting (python.linting.) | VS Code category mapping |
---|---|---|
W | pycodestyleCategorySeverity.W | Warning |
E | pycodestyleCategorySeverity.E | Error |
Prospector
Command-line arguments and configuration files
See Prospector Command Line Usage for general options. For example, to set a strictness level of «very high,» add the following line to your settings.json file:
Message category mapping
The Python extension maps all Prospector errors and warnings to the Error (E) category.
Flake8
Command-line arguments and configuration files
See Invoking Flake8 for general switches. For example, to ignore error E303 (too many blank lines), use the following setting:
By default, Flake8 ignores E121, E123, E126, E226, E24, and E704.
Flake8 user options are read from the C:\Users\ \.flake8 (Windows) or
/.config/flake8 (macOS/Linux) file.
Message category mapping
The Python extension maps flake8 message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.
Flake8 category | Applicable setting (python.linting.) | VS Code category mapping |
---|---|---|
F | flake8CategorySeverity.F | Error |
E | flake8CategorySeverity.E | Error |
W | flake8CategorySeverity.W | Warning |
Message category mapping
The Python extension maps mypy message categories to VS Code categories through the following settings. If desired, change the setting to change the mapping.
Как создавать окружения Python в Visual Studio и управлять ими
Окружение Python представляет собой контекст, в котором выполняется код Python. Различают глобальные, виртуальные окружения и окружения Conda. Окружение состоит из интерпретатора, библиотеки (обычно это стандартная библиотека Python) и нескольких установленных пакетов. Вместе они определяют языковые конструкции и синтаксис, доступные возможности операционной системы и пригодные для использования пакеты.
В Visual Studio для Windows есть окно Окружения Python, которое позволяет управлять окружениями и выбрать одно из них в качестве окружения по умолчанию для новых проектов. Все это мы рассмотрим в этой статье. Другие связанные с окружениями аспекты описаны в следующих статьях:
Для каждого конкретного проекта можно выбрать конкретное окружение вместо варианта по умолчанию.
Дополнительные сведения о создании и использовании виртуальных окружений для проектов Python см. в разделе Использование виртуальных окружений.
Если вы хотите установить пакеты в окружении, см. справочник по вкладке «Пакеты».
Чтобы установить другой интерпретатор Python, см. раздел Установка интерпретаторов Python. Как правило, если вы скачиваете и запускаете установщик для основного дистрибутива Python, Visual Studio обнаруживает эту новую установку, это окружение отображается в окне Окружения Python и может быть выбрано для проектов.
Если вы только начинаете работу с Python в Visual Studio, можете ознакомиться с базовыми сведениями в следующих статьях:
Окно «Окружения Python»
Окружения, обнаруженные Visual Studio, отображаются в окне Окружения Python. Чтобы открыть это окно, используйте один из следующих методов:
В любом случае окно Окружения Python открывается на одном уровне с Обозревателем решений:
Visual Studio ищет установленные глобальные окружения с помощью реестра (следуя по PEP 514), а также виртуальные окружения и окружения Conda (см. Типы окружений). Если нужное окружение не отображается в списке, ознакомьтесь с разделом Указание существующего окружения вручную.
При выборе окружения в списке на вкладке Обзор Visual Studio отображаются различные свойства и команды для этого окружения.
Например, как видно на рисунке выше, интерпретатор находится в папке C:\Python36-32. Четыре команды в нижней части вкладки Обзор открывают командную строку с выполняющимся интерпретатором. Дополнительные сведения см. в статье Справочная информация по вкладкам окна «Окружения Python»-2019 — обзор.
Например, на рисунке видно, что интерпретатор находится в папке C:\Program Files (x86)\Microsoft Visual Studio\Python310. Четыре команды в нижней части вкладки Обзор открывают командную строку с выполняющимся интерпретатором. Дополнительные сведения см. в статье Справочная информация по вкладкам окна «Окружения Python»-2022 — обзор.
Используйте раскрывающийся список под списком окружений для перехода к различным вкладкам, таким как Пакеты и IntelliSense. Эти вкладки также описаны в справочнике по вкладкам окна «Окружения Python».
Выбор окружения не влияет на его связи с любыми проектами. Окружение по умолчанию, выделенное полужирным шрифтом в списке, используется Visual Studio для любых новых проектов. Чтобы использовать другое окружение для новых проектов, используйте команду Назначить это окружение по умолчанию для новых проектов. В контексте проекта всегда можно выбрать конкретное окружение. Дополнительные сведения см. в разделе о выборе окружения для проекта.
Справа от каждого окружения в списке есть элемент управления, который позволяет открыть интерактивное окно для этого окружения. (В Visual Studio 2017 15.5 и более ранних версиях может отображаться другой элемент управления. Он предназначен для обновления базы данных IntelliSense для этого окружения. Дополнительные сведения о базе данных см. в разделе об окне окружений.)
Если окно Окружения Python развернуто достаточно широко, вы получите более полное представление окружений. Такой вариант может оказаться для вас более удобным.
Если окно Окружения Python развернуто достаточно широко, вы получите более полное представление окружений. Такой вариант может оказаться для вас более удобным.
Несмотря на то что Visual Studio учитывает параметр system-site-packages, его нельзя изменить из среды Visual Studio.
Что делать, если окружения не отображаются?
Если окружения не отображаются, значит Visual Studio не удалось обнаружить ни одной установки Python в стандартных расположениях. Такое может случиться, если после установки Visual Studio 2017 или более поздней версии вы очистили все параметры интерпретаторов в настройках установщика для рабочей нагрузки Python. Возможно, вы не установили интерпретатор для Visual Studio 2015 или более ранней версии. Дополнительные сведения см. в статье Установка интерпретаторов Python.
Если вы точно знаете, что на компьютере установлен интерпретатор Python, но Visual Studio (любая версия) не может его обнаружить, укажите его расположение вручную с помощью команды + Настраиваемый. Дополнительные сведения см. в следующем разделе Указание существующего окружения вручную.
Типы окружений
Visual Studio может работать с глобальными, виртуальными окружениями и окружениями Conda.
Глобальные среды
Каждая установка Python поддерживает собственное глобальное окружение. Например, Python 2.7, Python 3.6, Python 3.7, Anaconda 4.4.0 и т. д. См. Установка интерпретаторов Python.
Каждое окружение состоит из определенного интерпретатора Python, его стандартной библиотеки, набора предварительно установленных пакетов и любых дополнительных пакетов, устанавливаемых при активации этого окружения. Установив пакет в глобальном окружении, мы предоставляем к нему доступ для всех проектов, в которых оно используется. Если окружение находится в защищенной области файловой системы (например, в C:\Program files), для установки пакетов требуются права администратора.
Глобальные окружения доступны для всех проектов на компьютере. В Visual Studio вы можете выбрать одно глобальное окружение по умолчанию, которое будет использоваться для всех проектов, если вы не укажете другое для определенного проекта. Дополнительные сведения см. в разделе о выборе окружения для проекта.
Виртуальные среды
Работа в глобальном окружении — это простой способ приступить к работе. Со временем окружения будут перегружены множеством разных пакетов, установленных для различных проектов. Такой объем содержимого затрудняет тщательное тестирование приложения на соответствие определенному набору пакетов с известными версиями. Но тип окружения будет таким, как выше, который вы настроили бы для сервера сборки или на веб-сервере. Когда двум проектам требуются несовместимые пакеты или разные версии одного пакета, могут возникать конфликты.
По этой причине разработчики часто создают для проекта виртуальное окружение. Виртуальное окружение представляет собой вложенную папку в проекте, содержащую копию конкретного интерпретатора. При активации виртуального окружения все устанавливаемые вами пакеты устанавливаются только во вложенной папке этого окружения. При последующем запуске программы Python в этом окружении вы знаете, что она выполняется с использованием только этих конкретных пакетов.
Visual Studio предоставляет прямую поддержку для создания виртуального окружения для проекта. Например, если открыть проект, содержащий файл requirements.txt, или создать проект из шаблона, который включает этот файл, Visual Studio предложит автоматически создать виртуальное окружение и установить эти зависимости.
Вы можете создать виртуальное окружение в открытом проекте в любой момент. В Обозревателе решений разверните узел проекта, щелкните правой кнопкой мыши элемент Окружения Python и выберите Добавить окружение. В окне Добавить окружение выберите Виртуальное окружение.
В Visual Studio также доступна команда для создания файла requirements.txt из виртуального окружения, что позволяет легко воссоздать окружение на других компьютерах. См. дополнительные сведения о виртуальных окружениях.
Окружения Conda
Окружение Conda создается с помощью средства conda или интегрированного управления Conda в Visual Studio 2017 версии 15.7 и более поздних версий. (Требуется Anaconda или Miniconda, которые можно установить через Visual Studio Installer, подробнее см. в разделе Установка Visual Studio 2017.)
Выберите + Добавить окружение в окне Окружения Python (или на панели инструментов Python), чтобы открыть диалоговое окно Добавление окружения.
В диалоговом окне «Добавление окружения» выберите вкладку Окружение Conda:
Настройте следующие поля:
При создании среды Conda обязательно укажите хотя бы одну версию Python или пакет Python с помощью environments.yml или списка пакетов, чтобы окружение содержало среду выполнения Python. В противном случае Visual Studio игнорирует окружение, то есть оно не отображается в окне Окружения Python и его нельзя задать в качестве текущего окружения для проекта и глобального окружения.
Выберите Создать и отслеживайте ход выполнения в окне вывода.
Выходные данные после завершения создания возвращают несколько инструкций CLI:
В Visual Studio можно активировать окружение conda для проекта так же, как любое другое окружение, как описано в статье Выбор окружения для проекта.
Установить дополнительные пакеты в окружении можно на вкладке Пакеты.
Выберите + Добавить окружение в окне Окружения Python (или на панели инструментов Python), чтобы открыть диалоговое окно Добавление окружения.
В диалоговом окне «Добавление окружения» выберите вкладку Окружение Conda:
Настройте следующие поля:
При создании среды Conda обязательно укажите хотя бы одну версию Python или пакет Python с помощью environments.yml или списка пакетов, чтобы окружение содержало среду выполнения Python. В противном случае Visual Studio игнорирует окружение, то есть оно не отображается в окне Окружения Python и его нельзя задать в качестве текущего окружения для проекта и глобального окружения.
Выберите Создать и отслеживайте ход выполнения в окне вывода. Выходные данные после завершения создания возвращают несколько инструкций CLI:
В Visual Studio можно активировать окружение conda для проекта так же, как любое другое окружение, как описано в статье Выбор окружения для проекта.
Установить дополнительные пакеты в окружении можно на вкладке Пакеты.
Для оптимальной работы с окружениями conda используйте conda 4.4.8 или более поздней версии (версии conda отличаются от версий Anaconda). Вы можете установить подходящие версии Miniconda (Visual Studio 2019 и Visual Studio 2022) и Anaconda (Visual Studio 2017) через установщик Visual Studio.
Чтобы просмотреть версию conda, в которой хранятся окружения conda, и другие сведения, запустите conda info в командной строке Anaconda (то есть в командной строке, в пути которой указана Anaconda):
Папки окружения conda будут выглядеть следующим образом:
Поскольку окружения Conda не хранятся в проекте, они работают как глобальные окружения. Например, если установить пакет в окружении Conda, он станет доступным для всех проектов, в которых используется это окружение.
Для Visual Studio 2017 версии 15.6 и более ранних версий можно использовать окружения conda, указав на них вручную, как описано в разделе Указание существующего окружения вручную.
Visual Studio 2017 версии 15.7 и более поздних версий обнаруживает окружения conda автоматически и отображает их в окне Окружения Python, как описано в следующем разделе.
Указание существующего окружения вручную
Чтобы указать окружение, установленное в нестандартном расположении, выполните следующие действия:
Выберите + Добавить окружение в окне Окружения Python (или на панели инструментов Python), чтобы открыть диалоговое окно Добавление окружения.
В диалоговом окне «Добавление окружения» выберите вкладку Существующее окружение:
Щелкните раскрывающийся список Окружение и выберите Пользовательское:
Просмотрите предложенные значения и измените их при необходимости, а затем щелкните Добавить.
Сведения об окружении можно просмотреть и изменить в любое время в окне Окружения Python.
Выберите в этом окне нужное окружение Python и перейдите на вкладку Настройка.
Внеся изменения, выберите команду Применить. Вы также можете удалить окружение с помощью команды Удалить (недоступно для автоматически обнаруженных окружений). Дополнительные сведения см. в описании вкладки «Настройка».
Выберите + Добавить окружение в окне Окружения Python (или на панели инструментов Python), чтобы открыть диалоговое окно Добавление окружения.
В диалоговом окне «Добавление окружения» выберите вкладку Существующее окружение:
Например, выберите существующее окружение и путь к существующему окружению.
Щелкните раскрывающийся список Окружение и выберите Пользовательское:
.
Например, Anaconda 2021.05 в C:\Users\user\Anaconda3\python.exe
Просмотрите предложенные значения и измените их при необходимости, а затем щелкните Добавить.
Сведения об окружении можно просмотреть и изменить в любое время в окне Окружения Python.
Выберите в этом окне нужное окружение Python и перейдите на вкладку Настройка.
Внеся изменения, выберите команду Применить. Вы также можете удалить окружение с помощью команды Удалить (недоступно для автоматически обнаруженных окружений). Дополнительные сведения см. в описании вкладки «Настройка».
Исправление или удаление недопустимых сред
Если Visual Studio находит записи реестра для среды, но путь к интерпретатору недопустим, в окне Окружения Python отображается зачеркнутое имя.
Чтобы исправить нужную среду, попробуйте сначала использовать процесс исправления в установщике. Такая возможность есть, например, в установщиках для стандартной версии Python 3.x.
Измените реестр, чтобы исправить окружение, у которого нет возможности исправления, или удалить недопустимое окружение.
Чтобы изменить реестр напрямую, выполните следующие действия. Visual Studio автоматически обновляет окно Окружения Python при внесении изменений в реестр.
Запустите файл regedit.exe.
Перейдите к разделу HKEY_LOCAL_MACHINE\SOFTWARE\Python или HKEY_CURRENT_USER\SOFTWARE\Python. Если используется IronPython, вместо этого ищите IronPython.
Разверните узел, соответствующий дистрибутиву, например Python Core для CPython или ContinuumAnalytics для Anaconda. Если используется IronPython, разверните узел номера версии.
Проверьте значения в узле InstallPath.
Руководство. Работа с Python в Visual Studio
Python — это популярный язык программирования, который отличается надежностью, гибкостью и простотой освоения. Его можно бесплатно использовать на любых операционных системах. Он поддерживается широким сообществом разработчиков. Кроме того, для него доступно множество бесплатных библиотек. Этот язык поддерживает все виды разработки, в том числе веб-приложения, веб-службы, классические приложения, создание сценариев и научные вычисления. Поэтому Python используется множеством университетов, ученых, разработчиков-любителей и профессиональных разработчиков.
Visual Studio обеспечивает первоклассную поддержку языка Python. В этом учебнике рассматриваются перечисленные ниже действия.
Предварительные требования
Вы также можете использовать более раннюю версию Visual Studio с установленным подключаемым модулем Инструменты Python для Visual Studio. См. руководство по установке поддержки Python в Visual Studio.
Шаг 1. Создание проекта Python
С помощью проекта в Visual Studio производится управление всеми файлами, составляющими приложение. К файлам приложения можно отнести исходный код, ресурсы, конфигурации. Проект формализует и поддерживает связи между всеми файлами проекта. Проект также управляет внешними ресурсами, которые являются общими для нескольких проектов. Проект позволяет приложению легко расширяться и увеличивать свой размер. Использовать проекты гораздо проще, чем вручную контролировать связи с помощью специальных папок, скриптов, текстовых файлов и собственной памяти.
В этом учебнике вы начнете работу с простого проекта, содержащего один пустой файл кода.
В Visual Studio выберите Файл>Создать>Проект (CTRL+SHIFT+N), после чего откроется диалоговое окно Создание проекта. В нем можно просмотреть шаблоны для разных языков, после чего выбрать один из них для вашего проекта и указать, куда среда Visual Studio должна поместить файлы.
Чтобы просмотреть шаблоны Python, выберите Установленные>Python в области слева или выполните поиск по слову «Python». Поиск — это отличный способ найти шаблон, если вы не помните, где он находится в дереве языков.
Поддержка Python в Visual Studio включает в себя несколько шаблонов проектов, включая веб-приложения на платформах Bottle, Flask и Django. Однако для целей данного пошагового руководства мы начнем с пустого проекта.
Выберите шаблон Приложение Python, укажите имя проекта и нажмите кнопку ОК.
Через несколько секунд в окне обозревателя решений Visual Studio (1) будет показана структура проекта. Файл кода по умолчанию откроется в редакторе (2). Кроме того, откроется окно Свойства (3), в котором приводятся дополнительные сведения для элемента, выбранного в обозревателе решений, включая его точное расположение на диске.
Потратьте несколько минут на знакомство с обозревателем решений, который служит для просмотра файлов и папок проекта.
(1) Полужирным шрифтом выделен ваш проект, имя которого вы указали в окне Создание проекта. На диске этот проект представлен файлом .pyproj в папке проекта.
(2) На верхнем уровне находится решение, имя которого по умолчанию совпадает с именем проекта. Решение, представленное на диске файлом SLN, является контейнером для одного или нескольких связанных проектов. Например, если вы создаете расширение C++ для приложения Python, этот проект C++ может входить в то же решение. Решение также может включать в себя проект веб-службы и проекты специальных тестовых программ.
(3) В проекте можно увидеть файлы исходного кода. В нашем примере это один файл .py. При выборе файла его свойства приводятся в окне Свойства. Если дважды щелкнуть файл, он откроется в соответствующем средстве.
(4) Кроме того, в проекте есть узел Окружения Python. Если развернуть его, можно увидеть доступные интерпретаторы Python. Развернув узел интерпретатора, вы увидите библиотеки, установленные в этой среде (5).
Щелкните правой кнопкой мыши любой узел или элемент в обозревателе решений, чтобы открыть меню с применимыми командами. Например, команда Переименовать позволяет изменить имя любого узла или элемента, включая проект и решение.
В Visual Studio последовательно выберите Файл>Создать>Проект или нажмите комбинацию клавиш CTRL+SHIFT+N. Откроется экран Создание проекта, где можно искать и просматривать шаблоны на разных языках.
Чтобы просмотреть шаблоны Python, выполните поиск по слову python. Поиск — это отличный способ найти шаблон, если вы не помните, где он находится в дереве языков.
Поддержка Python в Visual Studio включает в себя несколько шаблонов проектов, таких как веб-приложения на платформах Bottle, Flask и Django. Для целей этого учебника мы начнем работу с пустого проекта.
Выберите шаблон PythonConsoleApp и нажмите кнопку Далее.
На экране Настроить новый проект укажите имя и расположение файла проекта, а затем нажмите кнопку Создать.
Новый проект откроется в Visual Studio.
Ознакомьтесь с Обозревателем решений, который можно использовать для просмотра файлов и папок проекта.
На верхнем уровне находится решение, имя которого по умолчанию совпадает с именем проекта (1).
Решение, представленное на диске файлом .sln, является контейнером для одного или нескольких связанных проектов. Например, если вы создаете расширение C++ для приложения Python, этот проект C++ может входить в то же решение. Решение также может включать в себя проект веб-службы и проекты специальных тестовых программ.
В проекте можно увидеть исходные файлы. В нашем примере это один файл PY ( (3) ). При выборе файла его свойства приводятся в окне Свойства. Если дважды щелкнуть файл, он откроется в соответствующем средстве.
Кроме того, в проекте есть узел Окружения Python ( (4) ). Разверните узел, чтобы отобразить доступные интерпретаторы Python.
Щелкните правой кнопкой мыши любой узел или элемент в Обозревателе решений, чтобы открыть контекстное меню с применимыми командами. Например, с помощью команды Переименовать можно изменить имя любого узла или элемента, в том числе проекта и решения.
Установка поддержки Python в Visual Studio
Поддержка Python сейчас доступна только в Visual Studio для Windows. В Mac и Linux поддержка Python доступна через Visual Studio Code.
Скачайте и запустите последнюю версию Visual Studio Installer для Windows. Поддержка Python доступна в выпуске 15.2 и выше. Если вы уже установили Visual Studio, откройте этот продукт и запустите установщик, выбрав Сервис>Получить средства и компоненты.
Выпуск Community предназначен для индивидуальных разработчиков, использования при аудиторном обучении и в научных исследованиях, а также разработки решений с открытым кодом. Если программу планируется использовать в других целях, установите Visual Studio Professional или Visual Studio Enterprise.
Установщик предоставляет список рабочих нагрузок, которые представляют собой группы связанных параметров для конкретных областей разработки. Для Python выберите рабочую нагрузку Разработка на Python и нажмите Установить.
Step 2: Write and run code
Although Solution Explorer is where you manage project files, the editor window is typically where you work with the contents of files, like source code. The editor is contextually aware of the type of file you’re editing. The editor also recognizes the programming language (based on the file extension), and offers features appropriate to that language such as syntax coloring and auto-completion using IntelliSense.
When you create a new «Python Application» project, a default empty file named PythonApplication1.py is opened in the Visual Studio editor.
In the editor, start typing print(«Hello, Visual Studio») and notice how Visual Studio IntelliSense displays autocompletion options along the way. The outlined option in the drop-down list is the default completion that’s used when you press the Tab key. Completions are most helpful when longer statements or identifiers are involved.
IntelliSense shows different information based on the statement you’re using, the function you’re calling, and so on. With the print function, typing ( after print to indicate a function call displays full usage information for that function. The IntelliSense pop up also shows the current argument in boldface (value as shown here):
Complete the statement so it matches the code below:
Because one’s development environment is a very personal matter, Visual Studio gives you complete control over Visual Studio’s appearance and behavior. Select the Tools > Options menu command and explore the settings under the Environment and Text Editor tabs. By default you see only a limited number of options; to see every option for every programming language, select Show all settings at the bottom of the dialog.
Run the code you’ve written to this point by pressing Ctrl+F5 or selecting Debug > Start without Debugging menu item. Visual Studio warns you if you still have errors in your code.
When you run the program, a console window will display the results. It’s similar to running a Python interpreter with PythonApplication1.py from the command line. Press any key to close the window and return to the Visual Studio editor.
On the next line, type from to again see a list of modules:
Finish by importing the cos and radians members, noticing the autocompletions available for each. When you’re done, your code should appear as follows:
Add a little more code to print the cosine values for 360 degrees:
Run the program again with Ctrl+F5 or Debug > Start without Debugging. Close the output window when you’re done.
Шаг 2. Написание и запуск кода
Хотя управление файлами проекта осуществляется в обозревателе решений, с содержимым файлов, например файлов исходного кода, вы обычно работаете в окне редактора. Редактор распознает тип редактируемого файла с учетом контекста. Он также определяет язык программирования (благодаря расширению файла) и обеспечивает характерные для этого языка возможности, например раскраску синтаксических конструкций и автоматическое завершение с помощью IntelliSense.
При создании проекта «Python Application» в редакторе Visual Studio откроется пустой файл по умолчанию с именем PythonApplication1.py.
Функция IntelliSense отображает различные сведения на основе используемого оператора, вызываемой функции и т. д. Если в функции print ввести ( после print для указания вызова функции, будет показана полная информация об использовании этой функции. Во всплывающем окне IntelliSense также полужирным шрифтом выделяется текущий аргумент (в этом случае это value):
Допишите оператор, чтобы он соответствовал следующему коду:
Visual Studio предоставляет полный контроль над внешним видом и поведением среды разработки, что позволяет настроить ее, как вам нравится. Выберите пункт меню Сервис>Параметры и изучите параметры на вкладках Среда и Текстовый редактор. По умолчанию вы видите ограниченный набор параметров. Чтобы просмотреть все параметры для каждого языка программирования, щелкните Показать все параметры внизу диалогового окна.
Чтобы выполнить весь написанный код, нажмите клавиши CTRL+F5 или выберите команду меню Отладка>Запуск без отладки. Если в коде все еще есть ошибки, в Visual Studio будут выведены предупреждения.
Во время выполнения программы в окне консоли будут отображаться результаты. Это напоминает запуск интерпретатора Python с файлом PythonApplication1.py из командной строки. Чтобы закрыть это окно и вернуться в редактор Visual Studio, нажмите любую клавишу.
Принцип функции завершения заключается в следующем — по мере ввода появляются подстроки со словами, в которых совпадают части или буквы в начале слова, и даже отображаются пропущенные символы. Дополнительные сведения см. в руководстве по редактированию кода.
Добавьте еще код для печати значений косинуса в интервале до 360 градусов.
Снова запустите программу, нажав клавиши CTRL+F5 или выбрав пункт меню Отладка>Запуск без отладки. По завершении закройте окно вывода.
Debug your Python code
Visual Studio provides a comprehensive debugging experience for Python, including attaching to running processes, evaluating expressions in the Watch and Immediate windows, inspecting local variables, breakpoints, step in/out/over statements, Set Next Statement, and more.
Also see the following scenario-specific debugging articles:
Python in Visual Studio supports debugging without a project. With a stand-alone Python file open, right-click in the editor, select Start with Debugging, and Visual Studio launches the script with the global default environment (see Python environments) and no arguments. But from then on, you have full debugging support.
To control the environment and arguments, create a project for the code, which is easily done with the From existing Python code project template.
Basic debugging
The basic debugging workflow involves settings breakpoints, stepping through code, inspecting values, and handling exceptions as described in the following sections.
A debugging session starts with the Debug > Start Debugging command, the Start button on the toolbar, or the F5 key. These actions launch your project’s startup file (shown in bold in Solution Explorer) with the project’s active environment and any command-line arguments or search paths that have been specified in Project Properties (see Project debugging options). Visual Studio 2017 version 15.6 and later alerts you if you don’t have a startup file set; earlier versions may open an output window with the Python interpreter running, or the output window briefly appears and disappears. In any case, right-click the appropriate file and select Set as Startup File.
The debugger always starts with the active Python environment for the project. To change the environment, make a different one active as described on Select a Python environment for a project.
Breakpoints
Breakpoints stop execution of code at a marked point so you can inspect the program state. Set breakpoints by clicking in the left margin of the code editor or by right-clicking a line of code and selecting Breakpoint > Insert Breakpoint. A red dot appears on each line with a breakpoint.
Clicking the red dot or right-clicking the line of code and selecting Breakpoint > Delete Breakpoint removes the breakpoint. You can also disable it without removing it using the Breakpoint > Disable Breakpoint command.
Some breakpoints in Python can be surprising for developers who have worked with other programming languages. In Python, the entire file is executable code, so Python runs the file when it’s loaded to process any top-level class or function definitions. If a breakpoint has been set, you may find the debugger breaking part-way through a class declaration. This behavior is correct, even though it’s sometimes surprising.
You can customize the conditions under which a breakpoint is triggered, such as breaking only when a variable is set to a certain value or value range. To set conditions, right-click the breakpoint’s red dot, select Condition, then create expressions using Python code. For full details on this feature in Visual Studio, see Breakpoint conditions.
When setting conditions, you can also set Action and create a message to log to the output window, optionally continuing execution automatically. Logging a message creates what is called a tracepoint without adding logging code to your application directly:
Step through code
Once stopped at a breakpoint, you have various ways to step through code or run blocks of code before breaking again. These commands are available in a number of places, including the top debug toolbar, the Debug menu, on the right-click context menu in the code editor, and through keyboard shortcuts (though not all commands are in all places):
Feature | Keystroke | Description |
---|---|---|
Continue | F5 | Runs code until the next breakpoint is reached. |
Step Into | F11 | Runs the next statement and stops. If the next statement is a call to a function, the debugger stops at the first line of the function being called. |
Step Over | F10 | Runs the next statement, including making a call to a function (running all its code) and applying any return value. Stepping over allows you to easily skip functions that you do not need to debug. |
Step Out | Shift+F11 | Runs code until the end of the current function, then steps to the calling statement. This command is useful when you don’t need to debug the remainder of the current function. |
Run to Cursor | Ctrl+F10 | Runs code up to the location of the caret in the editor. This command allows you to easily skip over a segment of code that you don’t need to debug. |
Set Next Statement | Ctrl+Shift+F10 | Changes the current run point in the code to the location of the caret. This command allows you to omit a segment of code from being run at all, such as when you know the code is faulty or produces an unwanted side-effect. |
Show Next Statement | Alt+Num * | Returns you to the next statement to run. This command is helpful if you’ve been looking around in your code and don’t remember where the debugger is stopped. |
Inspect and modify values
When stopped in the debugger, you can inspect and modify the values of variables. You can also use the Watch window to monitor individual variables and custom expressions. (See Inspect variables for general details.)
To view a value using DataTips, simply hover the mouse over any variable in the editor. You can select the value to change it:
The Autos window (Debug > Windows > Autos) contains variables and expressions that are close to the current statement. You can double-click in the value column or select and press F2 to edit the value:
The Locals window (Debug > Windows > Locals) displays all variables that are in the current scope, which can again be edited:
For more on using Autos and Locals, see Inspect variables in the Autos and Locals windows.
The Watch windows (Debug > Windows > Watch > Watch 1-4) allow you to enter arbitrary Python expressions and view the results. Expressions are reevaluated for each step:
HTML, XML, and JSON visualizations appear in separate popup windows with syntax highlighting and tree views.
Exceptions
If an error occurs in your program during debugging, but you don’t have an exception handler for it, the debugger breaks at the point of the exception:
At this point you can inspect the program state, including the call stack. However, if you attempt to step through the code, the exception continues being thrown until it’s either handled or your program exits.
The Debug > Windows > Exception Settings menu command brings up a window in which you can expand Python Exceptions:
The checkbox for each exception controls whether the debugger always breaks when it’s raised. Check this box when you want to break more often for a particular exception.
By default, most exceptions break when an exception handler cannot be found in the source code. To change this behavior, right-click any exception and modify the Continue When Unhandled in User Code option. Clear this box when you want to break less often for an exception.
To configure an exception that doesn’t appear in this list, select the Add button to add it. The name must match the full name of the exception.
Project debugging options
By default, the debugger starts your program with the standard Python launcher, no command-line arguments, and no other special paths or conditions. Startup options are changed through the project’s debug properties accessed by right-clicking your project in Solution Explorer, selecting Properties, and selecting the Debug tab.
Launch mode options
Run options (search paths, startup arguments, and environment variables)
Immediate and Interactive windows
There are two interactive windows you can use during a debugging session: the standard Visual Studio Immediate window, and the Python Debug Interactive window.
The Immediate window (Debug > Windows > Immediate) is used for quick evaluation of Python expressions and inspection or assignment of variables within the running program. See the general Immediate window article for details.
The Python Debug Interactive window (Debug > Windows > Python Debug Interactive) is richer as it makes the full Interactive REPL experience available while debugging, including writing and running code. It automatically connects to any process started in the debugger using the Standard Python launcher (including processes attached through Debug > Attach to Process). It’s not, however, available when using mixed-mode C/C++ debugging.
The Debug Interactive window supports special meta-commands in addition to the standard REPL commands:
The standard debugger windows such as Processes, Threads, and Call Stack aren’t synchronized with the Debug Interactive window. Changing the active process, thread, or frame in the Debug Interactive window doesn’t affect the other debugger windows. Similarly, changing the active process, thread, or frame in the other debugger windows doesn’t affect the Debug Interactive window.
Use the legacy debugger
Visual Studio 2017 versions 15.8 and later use a debugger based on ptvsd version 4.1+. Visual Studio 2019 versions 16.5 and later use a debugger based on debugpy. These versions of the debugger are compatible with Python 2.7 and Python 3.5+. If you’re using Python 2.6, 3.1 to 3.4, or IronPython, Visual Studio shows the error, Debugger does not support this Python environment:
In these cases, you must use the older debugger (which is the default in Visual Studio 2017 versions 15.7 and earlier). Select the Tools > Options menu command, navigate to Python > Debugging, and select the Use legacy debugger option.
If you’ve installed an older version of ptvsd in the current environment (such as an earlier 4.0.x version, or a 3.x version required for remote debugging), Visual Studio may show an error or warning.
The error, Debugger package could not be loaded, appears when you’ve installed ptvsd 3.x:
In this case, select Use the legacy debugger to set the Use legacy debugger option, and restart the debugger.
The warning, Debugger package is outdated, appears when you’ve installed an earlier 4.x version of ptvsd:
Although you may choose to ignore the warning for some versions of ptvsd, Visual Studio may not work correctly.
To manage your ptvsd installation:
Navigate to the Packages tab in the Python Environments window.
Enter «ptvsd» in the search box and examine the installed version of ptvsd:
Alternately, you can update the ptvsd package to its newest version by following the instructions in the Troubleshooting section.
Troubleshooting
For Visual Studio 2019 (Version 16.4 and earlier) upgrade ptvsd
If you have issues with the debugger, first upgrade your version of the debugger as follows:
Navigate to the Packages tab in the Python Environments window.
If issues persist, please file an issue on the PTVS GitHub repository.
For Visual Studio 2019 version 16.5 and later, debugpy is part of the Visual Studio Python workload and is updated along with Visual Studio.
Enable debugger logging
In the course of investigating a debugger issue, Microsoft may ask you to enable and collect debugger logs that help in diagnosis.
The following steps enable debugging in the current Visual Studio session:
Open a command window in Visual Studio using the View > Other Windows > Command Window menu command.
Enter the following command:
Start debugging and go through whatever steps are necessary to reproduce your issue. During this time, debug logs appear in the Output window under Debug Adapter Host Log. You can then copy the logs from that window and paste into a GitHub issue, email, etc.
If Visual Studio stops responding or you aren’t otherwise able to access the Output window, restart Visual Studio, open a command window, and enter the following command:
See also
For complete details on the Visual Studio debugger, see Debugging in Visual Studio.
Шаг 2. Написание и запуск кода
Хотя управление файлами проекта осуществляется в обозревателе решений, с содержимым файлов, например файлов исходного кода, вы обычно работаете в окне редактора. Редактор распознает тип редактируемого файла с учетом контекста. Он также определяет язык программирования (благодаря расширению файла) и обеспечивает характерные для этого языка возможности, например раскраску синтаксических конструкций и автоматическое завершение с помощью IntelliSense.
При создании проекта «Python Application» в редакторе Visual Studio откроется пустой файл по умолчанию с именем PythonApplication1.py.
Функция IntelliSense отображает различные сведения на основе используемого оператора, вызываемой функции и т. д. Если в функции print ввести ( после print для указания вызова функции, будет показана полная информация об использовании этой функции. Во всплывающем окне IntelliSense также полужирным шрифтом выделяется текущий аргумент (в этом случае это value):
Допишите оператор, чтобы он соответствовал следующему коду:
Visual Studio предоставляет полный контроль над внешним видом и поведением среды разработки, что позволяет настроить ее, как вам нравится. Выберите пункт меню Сервис>Параметры и изучите параметры на вкладках Среда и Текстовый редактор. По умолчанию вы видите ограниченный набор параметров. Чтобы просмотреть все параметры для каждого языка программирования, щелкните Показать все параметры внизу диалогового окна.
Чтобы выполнить весь написанный код, нажмите клавиши CTRL+F5 или выберите команду меню Отладка>Запуск без отладки. Если в коде все еще есть ошибки, в Visual Studio будут выведены предупреждения.
Во время выполнения программы в окне консоли будут отображаться результаты. Это напоминает запуск интерпретатора Python с файлом PythonApplication1.py из командной строки. Чтобы закрыть это окно и вернуться в редактор Visual Studio, нажмите любую клавишу.
Принцип функции завершения заключается в следующем — по мере ввода появляются подстроки со словами, в которых совпадают части или буквы в начале слова, и даже отображаются пропущенные символы. Дополнительные сведения см. в руководстве по редактированию кода.
Добавьте еще код для печати значений косинуса в интервале до 360 градусов.
Снова запустите программу, нажав клавиши CTRL+F5 или выбрав пункт меню Отладка>Запуск без отладки. По завершении закройте окно вывода.
Шаг 4. Выполнение кода в отладчике
Visual Studio предоставляет возможности для управления проектами, расширенные возможности редактирования, окно Интерактивный режим и инструменты полнофункциональной отладки для кода Python. В отладчике можно выполнять код пошагово, включая каждую итерацию цикла. Кроме того, можно приостанавливать программу, если выполняются определенные условия. При приостановке программы в отладчике можно полностью изучить ее состояние и изменить значения переменных. Эти действия необходимы для выявления источников ошибок в программе. Кроме того, они позволяют отслеживать поток работы программы.
Убедитесь, что код работает правильно, нажав клавишу F5 или выбрав команду меню Отладка>Начать отладку. Эта команда запускает код в отладчике. На сегодняшний день пока еще ничего не сделано для приостановки запущенной программы; просто выполняется печать шаблона волн для ряда итераций. Нажмите любую клавишу, чтобы закрыть окно вывода.
Чтобы закрыть окно вывода автоматически после завершения программы, выберите команду меню Сервис>Параметры, разверните узел Python, выберите Отладка и снимите флажок Ожидать входные данные при нормальном завершении работы процесса:
Дополнительные сведения об отладке и инструкции по настройке аргументов сценария и интерпретатора, см. в разделе Отладка кода Python.
Снова запустите отладчик (F5), и вы увидите, что выполнение кода остановится в строке с этой точкой останова. Здесь можно просмотреть стек вызовов и переменные. Переменные, относящиеся к области действия, приводятся в окне Видимые, если они определены. В нижней части этого окна можно также перейти к представлению Локальные.В нем отображаются все переменные, которые найдены средой Visual Studio в текущей области действия (включая функции), даже если они еще не определены.
Обратите внимание на панель инструментов отладки (показана ниже) в верхней части окна Visual Studio. Эта панель инструментов предоставляет быстрый доступ к наиболее часто используемым командам отладки (которые также находятся в меню Отладка).
Кнопки располагаются слева направо в следующем порядке:
Кнопка | Get-Help |
---|---|
Продолжить (F5) | Программа выполняется до следующей точки останова или до конца. |
Прервать все (Ctrl+Alt+Прервать) | Приостанавливает работу долго выполняющейся программы. |
Остановить отладку (Shift+F5) | Программа останавливается в текущем месте, и работа отладчика завершается. |
Перезапустить (Ctrl+Shift+F5) | Программа останавливается в текущем месте и перезапускается в отладчике с начала. |
Показать следующую инструкцию (ALT+NUM*) | Переключается на следующую строку кода для выполнения. Эта команда полезна в случае, если вы просматриваете код во время сеанса отладки и хотите быстро перейти к месту, где работа отладчика была приостановлена. |
Шаг с заходом (F11) | Выполняет следующую строку кода с заходом в вызываемые функции. |
Шаг с обходом (F10) | Выполняет следующую строку кода без захода в вызываемые функции. |
Шаг с выходом (Shift+F11) | Текущая функция выполняется до конца, после чего выполнение приостанавливается в вызывающем коде. |
Выполните применительно к оператору for шаг с обходом с помощью команды Шаг с обходом. Пошаговое выполнение означает, что отладчик выполняет текущую строку кода, включая все вызовы функций, после чего сразу приостанавливает выполнение программы. Обратите внимание на то, как в коде переменная i теперь определена в окнах Локальные и Видимые.
Выполните еще несколько шагов с обходом, наблюдая за тем, как меняются значения переменных в окнах Локальные и Видимые.
Пошаговое выполнение сотен итераций цикла может быть утомительным, поэтому в Visual Studio к точке останова можно добавить условие. В этом случае отладчик будет приостанавливать выполнение программы в точке останова, только если условие соблюдается. Например, можно настроить условие для точки останова в операторе for так, чтобы выполнение в ней прерывалось, только если значение переменной i превышает 1600. Чтобы задать это условие, щелкните правой кнопкой мыши красную точку, обозначающую точку останова, и выберите пункт Условия (сочетание клавиш Alt+F9>C). В появившемся всплывающем окне Параметры точки останова введите i > 1600 в качестве выражения и выберите Закрыть. Нажмите клавишу F5, чтобы продолжить работу, и обратите внимание на то, что до того, как произойдет следующий останов, будет выполнено несколько итераций.
Чтобы программа выполнялась до конца, отключите точку останова, щелкнув в поле точку правой кнопкой мыши и выбрав команду Выключить точку останова (CTRL+F9). Затем выберите команду Продолжить (или нажмите клавишу F5), чтобы запустить программу. Когда выполнение программы завершится, сеанс отладки в Visual Studio будет закрыт и вы вернетесь в режим редактирования. Можно также удалить точку останова, выбрав его точку или щелкнув правой кнопкой мыши точку и выбрав Удалить точку останова. При этом также удаляются все ранее заданные условия.
Tutorial: Work with Python in Visual Studio
Python is a popular programming language that is reliable, flexible, easy to learn, and free to use on all operating systems. Python is supported by both a strong developer community and many, free libraries. The language supports all kinds of development, including web applications, web services, desktop apps, scripting, and scientific computing. Many universities, scientists, casual developers, and professional developers use Python.
Visual Studio provides first-class language support for Python. This tutorial guides you through the following steps:
Prerequisites
You can also use an earlier version of Visual Studio with the Python Tools for Visual Studio installed. See Install Python support in Visual Studio.
Step 1: Create a new Python project
A project is how Visual Studio manages all the files that come together to produce a single application. Application files include source code, resources, and configurations. A project formalizes and maintains the relationships among all the project’s files. The project also manages external resources that are shared between multiple projects. A project allows your application to effortlessly expand and grow. Using projects is much easier than manually managing relationships in unplanned folders, scripts, text files, and your memory.
This tutorial begins with a simple project containing a single, empty code file.
In Visual Studio, select File > New > Project (Ctrl+Shift+N), which brings up the New Project dialog. Here you browse templates across different languages, then select one for your project and specify where Visual Studio places files.
To view Python templates, select Installed > Python on the left, or search for «Python». Using search is a great way to find a template when you can’t remember its location in the languages tree.
Python support in Visual Studio includes several project templates, including web applications using the Bottle, Flask, and Django frameworks. For the purposes of this walkthrough, however, let’s start with an empty project.
Select the Python Application template, specify a name for the project, and select OK.
After a few moments, Visual Studio shows the project structure in the Solution Explorer window (1). The default code file is open in the editor (2). The Properties window (3) also appears to show additional information for any item selected in Solution Explorer, including its exact location on disk.
Take a few moments to familiarize yourself with Solution Explorer, which is where you browse files and folders in your project.
(1) Highlighted in bold is your project, using the name you gave in the New Project dialog. On disk, this project is represented by a .pyproj file in your project folder.
(2) At the top level is a solution, which by default has the same name as your project. A solution, represented by a .sln file on disk, is a container for one or more related projects. For example, if you write a C++ extension for your Python application, that C++ project could be in the same solution. The solution might also contain a project for a web service, along with projects for dedicated test programs.
(3) Under your project you see source files, in this case only a single .py file. Selecting a file displays its properties in the Properties window. Double-clicking a file opens it in whatever way is appropriate for that file.
(4) Also under the project is the Python Environments node. When expanded, you see the Python interpreters that are available to you. Expand an interpreter node to see the libraries that are installed into that environment (5).
Right-click any node or item in Solution Explorer to access a menu of applicable commands. For example, the Rename command let’s you to change the name of any node or item, including the project and the solution.
In Visual Studio, select File > New > Project or press Ctrl+Shift+N. The Create a new project screen displays, where you can search and browse templates across different languages.
To view Python templates, search for python. Search is a great way to find a template when you can’t remember its location in the languages tree.
Python support in Visual Studio includes several project templates, such as web applications in the Bottle, Flask, and Django frameworks. For this tutorial, start with an empty project.
Select the PythonConsoleApp template, and select Next.
On the Configure your new project screen, specify a name and file location for the project, and then select Create.
The new project opens in Visual Studio.
Familiarize yourself with Solution Explorer, where you can browse files and folders in your project.
At the top level is the solution, which by default has the same name as your project (1).
A solution, which is shown as a .sln file on disk, is a container for one or more related projects. For example, if you write a C++ extension for your Python application, that C++ project can be in the same solution. The solution could also contain a project for a web service, and projects for dedicated test programs.
Your project, with the name you gave in the Create a new project dialog box, displays in bold (2). On disk, the project is a .pyproj file in your project folder.
Under your project are source files, in this case only a single .py file (3). Selecting a file displays its properties in the Properties window. Double-clicking a file opens it in whatever way is appropriate for that file.
Also under the project is the Python Environments node (4). Expand the node to show the available Python interpreters.
Expand an interpreter node to see the libraries installed in that environment (5).
Right-click any node or item in Solution Explorer to show a context menu of applicable commands. For example, Rename lets you change the name of a node or item, including the project and the solution.
Редактирование кода Python
Так как при разработке вы много работаете в редакторе кода, поддержка Python в Visual Studio предоставляет соответствующие функции для повышения продуктивности этой работы. К ним относятся выделение синтаксиса IntelliSense, автозавершение, справка по сигнатурам, переопределения методов, а также поиск и навигация.
Редактор также интегрируется с интерактивным окном в Visual Studio, упрощая обмен кодом между ними. Подробные сведения см. в разделах Учебник, шаг 3. Использование интерактивного окна REPL и Использование интерактивного окна. Команда «Отправить в интерактивное окно».
Общие сведения о редактировании кода в Visual Studio см. в статье Возможности редактора кода. Ознакомьтесь также со статьей Структура, чтобы узнать, как сконцентрироваться на определенных разделах кода.
Кроме того, с помощью обозревателя объектов Visual Studio (Вид>Другие окна>Обозреватель объектов или клавиши CTRL+W>J) вы можете проверять классы Python, определенные в каждом модуле, и функции, определенные в этих классах.
технология IntelliSense
Технология IntelliSense предоставляет следующие возможности: автозавершения, справка по сигнатурам, вывод кратких сведений и цветовая маркировка синтаксиса. Visual Studio 2017 версии 15.7 и более поздней также поддерживает подсказки по типам.
Для улучшения производительности функция IntelliSense в Visual Studio 2017 версии 15.5 и более ранних учитывает базу данных завершения, которая создается для каждого окружения Python в проекте. После добавления, удаления или обновления пакетов может потребоваться обновить базы данных. Их состояние отображается в окне Окружения Python (элемент того же уровня, что и обозреватель решений) на вкладке IntelliSense (см. дополнительные сведения об окне «Окружения»).
Visual Studio 2017 версии 15.6 и более поздних разными способами предоставляет функцию завершения IntelliSense, которая не зависит от базы данных.
Автозавершения
Автозавершения отображаются как операторы, идентификаторы и другие атрибуты, которые можно ввести в текущее расположение в редакторе. Автозавершения, отображаемые в списке, основываются на контексте, а также фильтруются для пропуска неправильных или ненужных параметров. Они часто инициируются при вводе различных инструкций (например, import ) и операторов (включая точку). Но их также можно отобразить в любое время, нажав клавиши CTRL+J>ПРОБЕЛ.
В открытом списке автозавершений можно выполнить поиск необходимого автозавершения с помощью клавиш со стрелками, мыши или путем ввода. Чем больше букв вы вводите, чем точнее фильтруется список для отображения возможных автозавершений. Кроме того, можно использовать следующие ярлыки:
Завершения элементов автоматически отображаются при вводе точки после переменной или значения. Вместе с ними отображаются методы и атрибуты потенциальных типов. Если переменная может быть нескольких типов, в списке содержатся все возможные варианты для всех типов с дополнительными сведениями для указания типов, поддерживающих каждое автозавершение. Если автозавершение поддерживается всеми возможными типами, оно отображается без заметки.
Элементы, которые начинаются и заканчиваются двумя символами подчеркивания, не отображаются по умолчанию. В общем случае к таким элементам не следует обращаться напрямую. Если же элемент нужен, введя два начальных символа подчеркивания, можно добавить эти завершения в список:
При использовании операторов raise и except отображаются списки классов, которые могут быть типами ошибок. При этом необязательно выводятся все определяемые пользователем исключения, но с их помощью можно быстро найти подходящие встроенные исключения.
При вводе символа @ запускается декоратор и отображаются потенциальные декораторы. Многие из этих элементов невозможно использовать в качестве декораторов. Чтобы определить, какие именно из них следует использовать, обратитесь к документации по библиотеке.
Вы можете настроить поведение автозавершений, выбрав Инструменты>Параметры>Текстовый редактор>Python>Дополнительно. Параметр Фильтрация списка по поисковой строке позволяет применить фильтрацию предложений автозавершения при вводе (флажок установлен по умолчанию), а при выборе параметра Завершение членов отображает пересечение членов отображаются только те автозавершения, которые поддерживают все возможные типы (флажок снят по умолчанию). См. раздел Параметры. Результаты завершения.
Подсказки по типам
Visual Studio 2017 версии 15.7 и более поздней.
Подсказки по типам в Python 3.5+ (PEP 484 (python.org) — это синтаксис аннотаций для функций и классов, который указывает на типы аргументов, возвращаемых значений и атрибутов класса. IntelliSense отображает подсказки по типам при наведении курсора на вызовы функций, аргументы и переменные с этими аннотациями.
В следующем примере можно увидеть, как аннотированные атрибуты класса Employee отображаются во всплывающем окне завершения IntelliSense для атрибута:
Полезно проверять подсказки по типам на протяжении проекта, поскольку ошибки обычно не возникают до выполнения. Для этой цели Visual Studio интегрирует стандартное средство MyPy через команду контекстного меню Python>Run Mypy в обозревателе решений:
При запуске команды отображается запрос на установку пакета mypy при необходимости. Затем Visual Studio запускает mypy для проверки подсказок по типам в каждом файле Python в проекте. Ошибки отображаются в окне Список ошибок в Visual Studio. При выборе элемента в окне вы перейдете к соответствующей строке в коде.
Использование команды Run Mypy в этом коде вызывает следующую ошибку:
В версиях Python, предшествующих 3.5, в Visual Studio также отображаются подсказки по типам, которые вы предоставляете через файлы-заглушки (.pyi). Файлы заглушки можно использовать всякий раз, когда вы не хотите включать подсказки по типам в код напрямую или необходимо создать подсказки по типам для библиотеки, которая не использует их напрямую. Дополнительные сведения см. в разделе Создание заглушек для модулей Python на вики-сайте проекта mypy.
Visual Studio содержит набор пакетов файлов Typeshed для Python 2 и 3, поэтому нет необходимости скачивать их отдельно. Но если вы хотите использовать другой набор файлов, можно указать путь в меню Средства>Параметры>Python>Языковой сервер. См. статью Параметры для Python в Visual Studio.
В настоящее время Visual Studio не поддерживает подсказки по типам в комментариях.
Справка по сигнатурам
Во время написания кода, вызывающего функцию, при вводе открывающейся скобки ( отображается справка по сигнатурам, а также доступные сведения о параметрах и документации. Ее также можно отобразить внутри вызова функции, нажав клавиши CTRL+SHIFT+ПРОБЕЛ. Хотя отображаемые сведения определяются строками документации в исходном коде функции, они содержат любые значения по умолчанию.
Чтобы отключить справку по сигнатурам, выберите Инструменты>Параметры>Текстовый редактор>Python>Общие и снимите флажок Завершение операторов>Сведения о параметрах.
Вывод кратких сведений
При наведении указателя мыши на идентификатор отображается подсказка. В зависимости от идентификатора в кратких сведениях могут отображаться потенциальные значения или типы, доступная документация, возвращаемые типы и расположения определений:
Цветовая маркировка синтаксиса
Цветовая маркировка синтаксиса — это функция, которая использует сведения, основанные на анализе кода, для выделения цветом переменных, операторов и других частей кода. Например, переменные, которые относятся к модулям или классам, могут выделяться другим цветом, нежели функции и остальные значения, а имена параметров могут отличаться цветом от локальных или глобальных переменных. (По умолчанию функции не выделяются полужирным шрифтом.)
Чтобы настроить цвета, выберите Инструменты>Параметры>Среда>Шрифты и цвета и измените записи Python в списке Отображение элементов.
Чтобы отключить цветовую маркировку синтаксиса, выберите Инструменты>Параметры>Текстовый редактор>Python>Дополнительно и снимите флажок Разные параметры>Имена цветов по типам. См. раздел Параметры. Прочие параметры.
Фрагменты кода
Фрагменты кода — это блоки, которые можно вставлять в файлы. Для этого введите сочетание клавиш и нажмите клавишу TAB или выберите команду Изменить>IntelliSense>Вставить фрагмент кода и Разместить во фрагменте, выберите Python, а затем нужный фрагмент кода.
Например, class является ярлыком для фрагмента кода, который вставляет определение класса. Вот фрагмент кода, который отображается в списке автозавершения при вводе class :
Если нажать клавишу TAB, будет создана остальная часть класса. Можно ввести имя и список базовых классов, перемещаясь между выделенными полями с помощью клавиши TAB, а затем нажав клавишу ВВОД, чтобы начать ввод текста.
Команды меню
При использовании команды меню Правка>IntelliSense>Вставить фрагмент кода сначала выберите Python, а затем — фрагмент кода:
Команда Правка>IntelliSense>Разместить во фрагменте точно так же помещает текущий выделенный фрагмент в текстовый редактор внутри выбранного структурного элемента. Предположим, у вас есть небольшой фрагмент кода:
Если выбрать этот код и команду Разместить во фрагменте, откроется список доступных фрагментов. Если выбрать def в списке, выбранный код будет помещен в определение функции. Вы сможете переходить между выделенным именем функции имя и аргументами с помощью клавиши TAB:
Просмотр доступных фрагментов кода
Доступные фрагменты кода можно просмотреть в диспетчере фрагментов кода. Чтобы открыть его, выберите пункт меню Инструменты>Диспетчер фрагментов кода и выберите Python в качестве языка:
Сведения о том, как создать собственные фрагменты кода, см. в статье Пошаговое руководство. Создание фрагмента кода.
Если вы написали качественный фрагмент кода, к которому вы хотите предоставить общий доступ, разместите его в репозитории и сообщите нам. Возможно, мы сможем включить его в следующий выпуск Visual Studio.
Навигация по коду
Поддержка Python в Visual Studio предоставляет несколько вариантов для быстрой навигации по коду, а также по библиотекам с доступным исходным кодом: Панель навигации, Перейти к определению, Перейти к и Найти все ссылки. Можно также использовать обозреватель объектов Visual Studio.
Панель переходов
Панель навигации отображается в верхней части каждого окна редактора и содержит двухуровневый список определений. Раскрывающийся список слева содержит определения классов и функций верхнего уровня в текущем файле. Раскрывающийся список справа отображает список определений в области, расположенной слева. При перемещении курсора в редакторе эти списки обновляются для отображения текущего контекста, при этом из них можно напрямую перейти к нужной записи.
Чтобы скрыть панель навигации, выберите Инструменты>Параметры>Текстовый редактор>Python>Общие и снимите флажок Параметры>Панель навигации.
Перейти к определению
Команда Перейти к определению позволяет быстро перейти от использования идентификатора (например, имени функции, класса или переменной) к определению в исходном коде. Ее можно вызвать, щелкнув правой кнопкой мыши идентификатор и выбрав Перейти к определению или поместив курсор внутрь этого идентификатора и нажав клавишу F12. Эта команда работает в коде и внешних библиотеках, если исходный код доступен. Если исходный код библиотеки недоступен, команда Перейти к определению переходит к соответствующему оператору import для ссылки на модуль или отображает ошибку.
Перейти к
Команда Правка>Перейти к (CTRL+, ) позволяет отобразить поле поиска в редакторе, где можно ввести любую строку и увидеть возможные совпадения в коде, определяющем функцию, класс или переменную. Она обеспечивает те же возможности, что и команда Перейти к определению, но без необходимости искать, где используется идентификатор.
Чтобы перейти к определению этого идентификатора, дважды щелкните любое имя или выберите его с помощью клавиш со стрелками и клавиши ВВОД.
Найти все ссылки
Найти все ссылки — это удобная команда для обнаружения, где используется и определен нужный идентификатор, включая операции импорта и назначения. Ее можно вызвать, щелкнув правой кнопкой мыши идентификатор и выбрав пункт Найти все ссылки или поместив курсор внутри этого идентификатора и нажав клавиши SHIFT+F12. Чтобы перейти к расположению элемента, нужно дважды щелкнуть его в списке.
Python
Microsoft
Python extension for Visual Studio Code
A Visual Studio Code extension with rich support for the Python language (for all actively supported versions of the language: >=3.7), including features such as IntelliSense (Pylance), linting, debugging, code navigation, code formatting, refactoring, variable explorer, test explorer, and more!
Support for vscode.dev
The Python extension does offer some support when running on vscode.dev (which includes github.dev). This includes partial IntelliSense for open files in the editor.
Installed extensions
The Python extension will automatically install the Pylance and Jupyter extensions to give you the best experience when working with Python files and Jupyter notebooks. However, Pylance is an optional dependency, meaning the Python extension will remain fully functional if it fails to be installed. You can also uninstall it at the expense of some features if you’re using a different language server.
Extensions installed through the marketplace are subject to the Marketplace Terms of Use.
Quick start
Set up your environment
Select your Python interpreter by clicking on the status bar
Configure the debugger through the Debug Activity Bar
Configure tests by running the Configure Tests command
Jupyter Notebook quick start
The Python extension and the Jupyter extension work together to give you a great Notebook experience in VS Code.
Open or create a Jupyter Notebook file (.ipynb) and start coding in our Notebook Editor!
For more information you can:
Useful commands
Open the Command Palette (Command+Shift+P on macOS and Ctrl+Shift+P on Windows/Linux) and type in one of the following commands:
Feature details
Learn more about the rich features of the Python extension:
IntelliSense: Edit your code with auto-completion, code navigation, syntax checking and more
Linting: Get additional code analysis with Pylint, Flake8 and more
Code formatting: Format your code with black, autopep or yapf
Debugging: Debug your Python scripts, web apps, remote or multi-threaded processes
Testing: Run and debug tests through the Test Explorer with unittest or pytest.
Jupyter Notebooks: Create and edit Jupyter Notebooks, add and run code cells, render plots, visualize variables through the variable explorer, visualize dataframes with the data viewer, and more
Environments: Automatically activate and switch between virtualenv, venv, pipenv, conda and pyenv environments
Refactoring: Restructure your Python code with variable extraction, method extraction and import sorting
Supported locales
Настройка VS Code для работы с Python.
Сегодня немного о моих мытарствах с VS Code и его настройкой для нормальной работы с Python разных версий. Сразу оговорюсь, что всё это настраивалось под меня, опыта у меня мало и вообще это большей частью “for fun”.
Редактор правда очень крутой, мощный (“навороченнее” какого-нибудь sublime text) и при этом очень лёгкий (запускается и работает шустрее PyCharm’a). Во всяком случае на мой неопытный взгляд (хотя авторитетные бобры тоже используют). Предполагается, что Python (2.x или 3.x, не важно) у вас уже установлен.
Скачать VS Code для Win, Mac и Linux можно совершенно бесплатно с официального сайта. Из коробки вы получаете редактор с IntelliSense, приятным дебагером, встроенной поддержкой Git и расширениями. Но для работы с Python этого недостаточно. Поэтому лезем во вкладку расширений, вбиваем в строке поиска “Python” и выбираем самое популярное расширение (1,5 млн мух, как мы знаем, ошибаться не могут). Жмём установить, немного ждём, перезапускаем приложение по требованию.
После установки он попросит установить pylint, но это не сложно сделать прямо здесь же из консоли:
На этом как бы и всё, формальная часть выполнена. Но. Сегодня мне понадобилось протестить один и тот же код на работоспособность в Python 2.7 и 3.6. В Ubuntu проблем не возникало: жмём Ctrl+Shift+P, ищем в появившемся меню “Python: Select Workspace Enterpreter” и выбираем нужное из списка. В Win10 почему-то это не сработало так просто: хотя на компьютере точно установлены 2.7, 3.5 и 3.6. в списке только 2.7. Как добавить элементы в этот список я не нашёл, но нашёл способ изменить и дебагер и текущую используемую версию python в файлах настроек.
Настраивается очень просто. При первом запуске дебагера вам будет предложено отредактировать конфигурацию, куда вам нужно дописать недостающие версии. Выглядит примерно так:
В этом блоке вам нужно изменить 2 строки: “ name” (имя конфигурации)и “ pythonPath” (путь до python.exe нужной версии). Не забудьте экранировать бэк-слэши:
Текущая версия интерпретатора.
Можно изменить в настройках приложения (файл settings.json). Нужно добавить следующее (Python 3.6):
Сохраняем настройки и теперь ваши скрипты будут исполняться интерпритатором Python 3.6.
Всё, указанное ниже, прописывается в файле settings.json
Я люблю всякие украшательства и использую встроенный пак иконок для разных типов файлов. Наглядно, стильно_модно_молодёжно.
Очень бывает удобно видеть количество пробелов перед строкой (особенно в python) и лишние пробелы между символами/словами:
Ну и красиво мигающий курсор ещё никому никогда не вредил 😉
Шаг 4. Выполнение кода в отладчике
Visual Studio предоставляет возможности для управления проектами, расширенные возможности редактирования, окно Интерактивный режим и инструменты полнофункциональной отладки для кода Python. В отладчике можно выполнять код пошагово, включая каждую итерацию цикла. Кроме того, можно приостанавливать программу, если выполняются определенные условия. При приостановке программы в отладчике можно полностью изучить ее состояние и изменить значения переменных. Эти действия необходимы для выявления источников ошибок в программе. Кроме того, они позволяют отслеживать поток работы программы.
Убедитесь, что код работает правильно, нажав клавишу F5 или выбрав команду меню Отладка>Начать отладку. Эта команда запускает код в отладчике. На сегодняшний день пока еще ничего не сделано для приостановки запущенной программы; просто выполняется печать шаблона волн для ряда итераций. Нажмите любую клавишу, чтобы закрыть окно вывода.
Чтобы закрыть окно вывода автоматически после завершения программы, выберите команду меню Сервис>Параметры, разверните узел Python, выберите Отладка и снимите флажок Ожидать входные данные при нормальном завершении работы процесса:
Дополнительные сведения об отладке и инструкции по настройке аргументов сценария и интерпретатора, см. в разделе Отладка кода Python.
Снова запустите отладчик (F5), и вы увидите, что выполнение кода остановится в строке с этой точкой останова. Здесь можно просмотреть стек вызовов и переменные. Переменные, относящиеся к области действия, приводятся в окне Видимые, если они определены. В нижней части этого окна можно также перейти к представлению Локальные.В нем отображаются все переменные, которые найдены средой Visual Studio в текущей области действия (включая функции), даже если они еще не определены.
Обратите внимание на панель инструментов отладки (показана ниже) в верхней части окна Visual Studio. Эта панель инструментов предоставляет быстрый доступ к наиболее часто используемым командам отладки (которые также находятся в меню Отладка).
Кнопки располагаются слева направо в следующем порядке:
Кнопка | Get-Help |
---|---|
Продолжить (F5) | Программа выполняется до следующей точки останова или до конца. |
Прервать все (Ctrl+Alt+Прервать) | Приостанавливает работу долго выполняющейся программы. |
Остановить отладку (Shift+F5) | Программа останавливается в текущем месте, и работа отладчика завершается. |
Перезапустить (Ctrl+Shift+F5) | Программа останавливается в текущем месте и перезапускается в отладчике с начала. |
Показать следующую инструкцию (ALT+NUM*) | Переключается на следующую строку кода для выполнения. Эта команда полезна в случае, если вы просматриваете код во время сеанса отладки и хотите быстро перейти к месту, где работа отладчика была приостановлена. |
Шаг с заходом (F11) | Выполняет следующую строку кода с заходом в вызываемые функции. |
Шаг с обходом (F10) | Выполняет следующую строку кода без захода в вызываемые функции. |
Шаг с выходом (Shift+F11) | Текущая функция выполняется до конца, после чего выполнение приостанавливается в вызывающем коде. |
Выполните применительно к оператору for шаг с обходом с помощью команды Шаг с обходом. Пошаговое выполнение означает, что отладчик выполняет текущую строку кода, включая все вызовы функций, после чего сразу приостанавливает выполнение программы. Обратите внимание на то, как в коде переменная i теперь определена в окнах Локальные и Видимые.
Выполните еще несколько шагов с обходом, наблюдая за тем, как меняются значения переменных в окнах Локальные и Видимые.
Пошаговое выполнение сотен итераций цикла может быть утомительным, поэтому в Visual Studio к точке останова можно добавить условие. В этом случае отладчик будет приостанавливать выполнение программы в точке останова, только если условие соблюдается. Например, можно настроить условие для точки останова в операторе for так, чтобы выполнение в ней прерывалось, только если значение переменной i превышает 1600. Чтобы задать это условие, щелкните правой кнопкой мыши красную точку, обозначающую точку останова, и выберите пункт Условия (сочетание клавиш Alt+F9>C). В появившемся всплывающем окне Параметры точки останова введите i > 1600 в качестве выражения и выберите Закрыть. Нажмите клавишу F5, чтобы продолжить работу, и обратите внимание на то, что до того, как произойдет следующий останов, будет выполнено несколько итераций.
Чтобы программа выполнялась до конца, отключите точку останова, щелкнув в поле точку правой кнопкой мыши и выбрав команду Выключить точку останова (CTRL+F9). Затем выберите команду Продолжить (или нажмите клавишу F5), чтобы запустить программу. Когда выполнение программы завершится, сеанс отладки в Visual Studio будет закрыт и вы вернетесь в режим редактирования. Можно также удалить точку останова, выбрав его точку или щелкнув правой кнопкой мыши точку и выбрав Удалить точку останова. При этом также удаляются все ранее заданные условия.
Работа с интерактивным окном Python
Visual Studio предоставляет интерактивное окно для цикла REPL (read–eval–print loop) отдельно для каждого окружения Python, что дает ряд преимуществ над интерфейсом REPL из командной строки python.exe. В интерактивном окне (открывается с помощью команд меню Просмотр>Другие окна> Интерактивное окно) можно ввести произвольный код Python и немедленно увидеть результаты. Это помогает вам изучать API и экспериментировать с ним, а также интерактивно разрабатывать рабочий код для добавления в проекты.
Visual Studio предоставляет ряд режимов REPL Python.
В этой статье описаны стандартный режим REPL и режим отладки REPL. Дополнительные сведения о режимах IPython см. в руководстве по использованию IPython в интерактивном окне.
Подробное пошаговое руководство с примерами, включая взаимодействие с редактором, например с помощью клавиш CTRL+ВВОД, см. в шаге 3 в руководстве: использование интерактивного окна REPL.
Открытие интерактивного окна
Существует несколько способов открыть для окружения интерактивное окно.
Первый способ — переключитесь в окно окружений Python (Просмотр>Другие окна>Окружения Python или CTRL+K>CTRL+` ) и выберите команду Открыть интерактивное окно или нажмите кнопку выбранного окружения.
Второй способ — в нижней части меню Просмотр>Другие окна находится команда Интерактивное окно Python для вашего окружения по умолчанию, а также команда для перехода в окно Окружения:
Other Windows» data-linktype=»relative-path»>
Третий способ — интерактивное окно можно открыть в файле запуска проекта или с помощью отдельного файла, выбрав команду меню Отладка>Выполнить файл в интерактивном окне Python (SHIFT+ALT+F5):
Наконец, можно выбрать код в файле и использовать описанную ниже команду Отправить код в интерактивное окно.
Параметры интерактивного окна
Вы можете управлять разными аспектами интерактивного окна с помощью меню Инструменты>Параметры>Python>Интерактивные окна (см. Параметры):
Работа с интерактивным окном Python
Интерактивное окно повышает удобство работы с обычными условиями цикла REPL в командной строке Python, автоматически выделяя отступами операторы, принадлежащие к окружающей области видимости. В журнале (можно отозвать с помощью стрелки вверх) также представлены многострочные элементы, в то время как в среде REPL с командной строкой содержатся только единичные строки.
Команды также допускают расширение с помощью расширений Visual Studio путем реализации и экспорта IInteractiveWindowCommand (пример).
Переключение областей видимости
По умолчанию область действия интерактивного окна проекта ограничена файлом запуска проекта, как и при запуске из командной строки. Для автономного файла действия выполняются в области этого файла. Но в любой момент сеанса REPL вы можете изменить область с помощью раскрывающегося меню в верхней части интерактивного окна:
Команда «Отправить код в интерактивное окно»
Кроме выполнения действий непосредственно в интерактивном окне, вы можете выбрать любой код в редакторе, щелкнуть его правой кнопкой мыши и выбрать Отправить в интерактивное окно или нажать клавиши CTRL+ВВОД.
Эта команда также удобна для итеративной или эволюционной разработки кода, включая тестирование кода по мере разработки. Например, после того как вы отправили фрагмент кода в интерактивное окно и увидели результат его выполнения, можно снова отобразить этот код нажатием стрелки «вверх», внести изменения и быстро проверить результат, нажав клавиши CTRL+ВВОД. (Нажатие клавиши ВВОД в конце входной строки также выполняет введенный код, но при нажатии этой клавиши в середине строки происходит вставка новой строки.) Внеся все необходимые изменения в код, можно легко скопировать его обратно в файл проекта.
Работа с ячейками кода
Ячейки кода, которые поддерживаются различными текстовыми редакторами, можно использовать в ходе анализа данных.
Поведение IntelliSense
В интерактивном окне применяется технология IntelliSense на основе используемых объектов, в отличие от редактора кода, в котором IntelliSense основывается только на анализе исходного кода. Эти предложения в интерактивном окне более точные, особенно при работе с динамически создаваемым кодом. Недостаток заключается в том, что функции с побочными эффектами (например, запись сообщений) могут повлиять на процесс разработки.
Если это является проблемой, измените параметры, выбрав Инструменты>Параметры>Python>Интерактивные окна в группе Режим завершения, как указано в описании параметров интерактивных окон.
Step 2: Write and run code
Although Solution Explorer is where you manage project files, the editor window is typically where you work with the contents of files, like source code. The editor is contextually aware of the type of file you’re editing. The editor also recognizes the programming language (based on the file extension), and offers features appropriate to that language such as syntax coloring and auto-completion using IntelliSense.
When you create a new «Python Application» project, a default empty file named PythonApplication1.py is opened in the Visual Studio editor.
In the editor, start typing print(«Hello, Visual Studio») and notice how Visual Studio IntelliSense displays autocompletion options along the way. The outlined option in the drop-down list is the default completion that’s used when you press the Tab key. Completions are most helpful when longer statements or identifiers are involved.
IntelliSense shows different information based on the statement you’re using, the function you’re calling, and so on. With the print function, typing ( after print to indicate a function call displays full usage information for that function. The IntelliSense pop up also shows the current argument in boldface (value as shown here):
Complete the statement so it matches the code below:
Because one’s development environment is a very personal matter, Visual Studio gives you complete control over Visual Studio’s appearance and behavior. Select the Tools > Options menu command and explore the settings under the Environment and Text Editor tabs. By default you see only a limited number of options; to see every option for every programming language, select Show all settings at the bottom of the dialog.
Run the code you’ve written to this point by pressing Ctrl+F5 or selecting Debug > Start without Debugging menu item. Visual Studio warns you if you still have errors in your code.
When you run the program, a console window will display the results. It’s similar to running a Python interpreter with PythonApplication1.py from the command line. Press any key to close the window and return to the Visual Studio editor.
On the next line, type from to again see a list of modules:
Finish by importing the cos and radians members, noticing the autocompletions available for each. When you’re done, your code should appear as follows:
Add a little more code to print the cosine values for 360 degrees:
Run the program again with Ctrl+F5 or Debug > Start without Debugging. Close the output window when you’re done.
Edit Python code
Because you spend much of your development time in the code editor, Python support in Visual Studio provides functionality to help you be more productive. Features include IntelliSense syntax highlighting, autocompletion, signature help, method overrides, search, and navigation.
For general documentation on editing code in Visual Studio, see Features of the code editor. Also see Outlining, which helps you stay focused on particular sections of your code.
You can also use the Visual Studio Object Browser (View > Other Windows > Object Browser or Ctrl+W > J) for inspecting Python classes defined in each module and the functions defined in those classes.
IntelliSense
IntelliSense provides completions, signature help, quick info, and code coloring. Visual Studio 2017 versions 15.7 and later also support type hints.
To improve performance, IntelliSense in Visual Studio 2017 version 15.5 and earlier depends on a completion database that’s generated for each Python environment in your project. Databases may need refreshing if you add, remove, or update packages. Database status is shown in the Python Environments window (a sibling of Solution Explorer) on the IntelliSense tab (see Environments window reference).
Visual Studio 2017 version 15.6 and later uses a different means to provide IntelliSense completions that aren’t dependent on the database.
Completions
Completions appear as statements, identifiers, and other words that may be appropriately entered at the current location in the editor. What’s shown in the list is based on context and is filtered to omit incorrect or distracting options. Completions are often triggered by typing different statements (such as import ) and operators (including a period), but you can have them appear at anytime by typing Ctrl+J > Space.
When a completion list is open, you can search for the completion you want using the arrow keys, the mouse, or by continuing to type. As you type more letters, the list is further filtered to show likely completions. You can also use shortcuts such as:
Member completions appear automatically when you type a period after a variable or value, along with the methods and attributes of the potential types. If a variable could be more than one type, the list includes all possibilities from all types, with extra information to indicate which types support each completion. Where a completion is supported by all possible types, it is shown without annotation.
By default, «dunder» members (members beginning and ending with a double underscore) are not shown. In general, such members should not be accessed directly. If you need one, however, typing the leading double underscore adds these completions to the list:
The raise and except statements display lists of classes likely to be error types. The list may not include all user-defined exceptions, but helps you find suitable built-in exceptions quickly:
Typing @ starts a decorator and shows potential decorators. Many of these items aren’t usable as decorators; check the library documentation to determine which to use.
Type hints
Visual Studio 2017 version 15.7 and later.
«Type hints» in Python 3.5+ (PEP 484 (python.org) is an annotation syntax for functions and classes that indicate the types of arguments, return values, and class attributes. IntelliSense displays type hints when you hover over functions calls, arguments, and variables that have those annotations.
In the following example, you can see how the annotated attributes of the Employee class appear in the IntelliSense completion popup for an attribute:
It’s also helpful to validate type hints throughout your project, because errors won’t normally appear until run time. For this purpose, Visual Studio integrates the industry standard MyPy tool through the context menu command Python > Run Mypy in Solution Explorer:
Running the command prompts you to install the mypy package, if needed. Visual Studio then runs mypy to validate type hints in every Python file in the project. Errors appear in the Visual Studio Error List window. Selecting an item in the window navigates to the appropriate line in your code.
Using the Run Mypy command on this code generates the following error:
For versions of Python before 3.5, Visual Studio also displays type hints that you supply through Typeshed stub files (.pyi). You can use stub files whenever you don’t want to include type hints directly in your code, or when you want to create type hints for a library that doesn’t use them directly. For more information, see Create stubs for Python modules in the mypy project wiki.
At present, Visual Studio doesn’t support type hints in comments.
Signature help
When writing code that calls a function, signature help appears when you type the opening ( and displays available documentation and parameter information. You can also make it appear with Ctrl+Shift+Space inside a function call. The information displayed depends on the documentation strings in the function’s source code, but includes any default values.
To disable signature help, go to Tools > Options > Text Editor > Python > General and clear Statement completion > Parameter information.
Quick info
Hovering the mouse pointer over an identifier displays a Quick Info tooltip. Depending on the identifier, Quick Info may display the potential values or types, any available documentation, return types, and definition locations:
Code coloring
Code coloring uses information from code analysis to color variables, statements, and other parts of your code. For example, variables that refer to modules or classes may be shown in a different color than functions or other values, and parameter names appear in a different color than local or global variables. (By default, functions aren’t shown in bold):
To customize the colors, go to Tools > Options > Environment > Fonts and Colors and modify the Python entries in the Display items list:
Code snippets
Code snippets are fragments of code that can be inserted into your files by typing a shortcut and pressing Tab, or using the Edit > IntelliSense > Insert Code Snippet and Surround With commands, selecting Python, then selecting the desired snippet.
For example, class is a shortcut for a code snippet that inserts a class definition. You see the snippet appear in the autocompletion list when you type class :
Pressing Tab generates the rest of the class. You can then type over the name and bases list, moving between the highlighted fields with Tab, then press Enter to begin typing the body.
Menu commands
When you use the Edit > IntelliSense > Insert Code Snippet menu command, you first select Python, then select a snippet:
The Edit > IntelliSense > Surround With command, similarly, places the current selection in the text editor inside a chosen structural element. For example, suppose you had a bit of code like the following:
Selecting this code and choosing the Surround With command displays a list of available snippets. Choosing def from the list places the selected code within a function definition, and you can use the Tab key to navigate between the highlighted function name and arguments:
Examine available snippets
You can see the available code snippets in the Code Snippets Manager, opened by using Tools > Code Snippets Manager menu command and selecting Python as the language:
If you write a great code snippet that you’d like to share, feel free to post it in a gist and let us know. We may be able to include it in a future release of Visual Studio.
Navigate your code
Python support in Visual Studio provides several means to quickly navigate within your code, including libraries for which source code is available: the navigation bar, Go To Definition, Navigate To, and Find All References. You can also use the Visual Studio Object Browser.
Navigation bar
The navigation bar is displayed at the top of each editor window and includes a two-level list of definitions. The left drop-down contains top-level class and function definitions in the current file; the right drop-down displays a list of definitions within the scope shown in the left. As you move around in the editor, the lists update to show your current context, and you can also select an entry from these lists to jump directly to.
To hide the navigation bar, go to Tools > Options > Text Editor > Python > General and clear Settings > Navigation bar.
Go To Definition
Go To Definition quickly jumps from the use of an identifier (such as a function name, class, or variable), to the source code where it’s defined. You invoke it by right-clicking an identifier and selecting Go To Definition or, by placing the caret in the identifier and pressing F12. It works across your code and external libraries provided that source code is available. If library source code is not available, Go To Definition jumps to the relevant import statement for a module reference, or displays an error.
Navigate To
The Edit > Navigate To command (Ctrl+,) displays a search box in the editor where you can type any string and see possible matches in your code that defines a function, class, or variable containing that string. This feature provides a similar capability as Go To Definition but without having to locate a use of an identifier.
Double-clicking any name, or selecting with arrow keys and Enter, navigates to the definition of that identifier.
Find All References
Find All References is a helpful way of discovering where any given identifier is both defined and used, including imports and assignments. You invoke it by right-clicking an identifier and selecting Find All References, or by placing the caret in the identifier and pressing Shift+F12. Double-clicking an item in the list navigates to its location.
Краткое руководство. Создание первого веб-приложения Python с помощью Visual Studio
В рамках этого краткого (на 5–10 минут) знакомства с Visual Studio в качестве IDE для Python создается простое веб-приложение Python на платформе Flask. Вы создадите проект при помощи дискретных действий, которые помогут ознакомиться с базовыми функциями Visual Studio.
Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. В установщике выберите рабочую нагрузку Разработка на Python.
Установите Visual Studio бесплатно со страницы скачиваемых материалов Visual Studio, если еще не сделали этого. В Visual Studio Installer выберите рабочую нагрузку Разработка на Python, а в сведениях об установке — Веб-поддержка в Python.
Создание проекта
Ниже приведены инструкции по созданию пустого проекта, который служит контейнером для приложения:
Запустите Visual Studio 2019.
На начальном экране выберите Создать новый проект.
В диалоговом окне Создать новый проект введите «Python веб» в поле поиска вверху, выберите Веб-проект в среднем списке и нажмите Далее:
В следующем диалоговом окне Настроить новый проект введите HelloPython в качестве имени проекта, укажите расположение и выберите Создать. (Имя решения автоматически устанавливается в соответствии с именем проекта.)
Новый проект откроется в обозревателе решений в правой области. Проект пока пуст, так как он не содержит других файлов.
Откройте Visual Studio 2022.
На начальном экране выберите Создать новый проект.
В диалоговом окне Создание проекта введите «Python web» в поле поиска вверху. Выберите Веб-проект из списка, а затем нажмите Далее:
Если вы не видите шаблоны веб-проекта Python, выберите пункт Средства>Get Tools and Features (Получить средства и компоненты), чтобы запустить Visual Studio Installer. В Installer выберите рабочую нагрузку Разработка на Python, а в разделе Сведения об установке щелкните Веб-поддержка в Python. Затем нажмите кнопку Изменить.
В диалоговом окне Настроить новый проект введите «HelloPython» в качестве имени проекта, укажите расположение, а затем выберите Создать. Поле Имя решения автоматически обновится в соответствии с именем проекта.
Новый проект откроется в обозревателе решений в правой области. Проект пока пуст, так как он не содержит других файлов.
Вопрос. В чем преимущество создания проекта в Visual Studio для приложений Python?
Ответ. Приложения Python обычно определяются только с помощью папок и файлов, однако такая простая структура может стать утомительной по мере увеличения размеров приложений. Приложения могут содержать автоматически созданные файлы, JavaScript для веб-приложений и другие компоненты. Проект Visual Studio помогает управлять этими сложными моментами.
Проект, PYPROJ-файл, определяет все исходные файлы и файлы содержимого, связанные с проектом. PYPROJ-файл содержит сведения о сборке для каждого файла, хранит информацию для интеграции с системами управления версиями и помогает упорядочить ваше приложение в виде логических компонентов.
Вопрос. Что представляет собой «решение», которое отображается в обозревателе решений?
Ответ. Решение Visual Studio — это контейнер, который помогает управлять одним или несколькими связанными проектами в виде группы. В решении хранятся параметры конфигурации, которые не относятся к конкретному проекту. Проекты в решении также могут ссылаться друг на друга. Например, при запуске проекта приложения Python может автоматически создаваться второй проект, например расширение C++, используемое приложением Python.
Установка библиотеки Flask
Веб-приложения на Python почти всегда используют одну из множества доступных библиотек Python для обработки низкоуровневых процессов, таких как маршрутизация веб-запросов и формирование ответов. Visual Studio предоставляет множество шаблонов для веб-приложений. Позже в этом кратком руководстве вы используете один из этих шаблонов.
А сейчас выполните следующие шаги, чтобы установить библиотеку Flask в глобальном окружении по умолчанию, которое Visual Studio использует для этого проекта.
Разверните в проекте узел Окружения Python, чтобы увидеть среду по умолчанию для проекта.
В поле поиска введите «flask». Если Flask отображается под полем поиска, этот шаг можно пропустить. В противном случае выберите Запустить команду: pip install flask. Подтвердите запросы на права администратора и наблюдайте за ходом выполнения в окне Вывод в Visual Studio. (Запрос на повышение прав выводится в том случае, если папка пакетов для глобальной среды находится в защищенной области, такой как C:\Program Files.)
Разверните в проекте узел Окружения Python, чтобы увидеть среду по умолчанию для проекта.
Щелкните окружение правой кнопкой мыши и выберите Открыть пакеты Python. Эта команда открывает вкладку Пакеты (PyPI) в окне Окружения Python.
В поле поиска введите «flask». Если Flask отображается под полем поиска, этот шаг можно пропустить. В противном случае выберите Выполнить команду: pip install flask.
Запрос на повышение прав отображается, если папка пакетов глобального окружения находится в защищенной области, например в папке C:\Program Files. Подтвердите запросы на права администратора. Следите за ходом выполнения в окне Вывод в Visual Studio.
После установки библиотека появится в среде в Обозревателе решений. Это означает, что ее можно использовать в коде Python.
Вместо установки библиотек в глобальном окружении разработчики обычно создают «виртуальное окружение», в котором устанавливаются библиотеки для определенного проекта. Шаблоны Visual Studio обычно обеспечивают такую возможность, как описано в кратком руководстве по созданию проекта Python с помощью шаблона.
Вопрос. Где можно подробнее узнать о других доступных пакетах Python?
Ответ. Перейдите к странице индекса пакетов Python.
Добавление файла кода
Теперь можно добавить немного кода на Python, чтобы реализовать простейшее веб-приложение.
Щелкните проект правой кнопкой мыши в обозревателе решений и выберите «Добавить>новый элемент«.
В открывшемся диалоговом окне выберите элемент Пустой файл Python, присвойте файлу имя app.py и нажмите кнопку Добавить. Файл автоматически откроется в редакторе кода Visual Studio.
Скопируйте следующий код и вставьте его в app.py:
Щелкните проект правой кнопкой мыши в обозревателе решений и выберите «Добавить>новый элемент«.
В появившемся диалоговом окне выберите Пустой. В качестве имени введите app.py, а затем нажмите кнопку Добавить. Файл автоматически откроется в редакторе кода Visual Studio.
Скопируйте следующий код и вставьте его в app.py:
Как вы могли заметить, в диалоговом окне Добавить>Создать элемент отображается много других типов файлов, которые можно добавить в проект Python, в том числе класс Python, пакет Python, модульный тест Python, файлы web.config и многое другое. Как правило, эти шаблоны элементов прекрасно подходят для быстрого создания файлов при помощи полезного стандартного кода.
Вопрос. Где можно подробнее узнать о Flask?
Ответ. Ознакомьтесь с документацией по Flask. Начать можно с краткого руководства по Flask.
Запуск приложения
В Обозревателе решений щелкните правой кнопкой мыши файл app.py, а затем в раскрывающемся меню выберите Задать как файл запуска. С помощью этой команды файл кода задается как запускаемый в Python при запуске приложения.
Выберите пункт Отладка>Запустить без отладки или нажмите сочетание клавиш Ctrl+F5, чтобы сохранить изменения в файлах и запустить приложение.
Если в командном окне отображается только интерактивная оболочка Python или если это окно появляется на экране и сразу исчезает, убедитесь, что файл app.py задан как файл запуска.
Закройте командное окно, чтобы остановить приложение, а затем закройте окно браузера.
Вопрос. В чем разница между командами «Запустить без отладки» и «Начать отладку»?
Ответ. Команда Начать отладку используется, чтобы запустить приложение в контексте отладчика Visual Studio. С помощью отладчика можно устанавливать точки останова, проверять переменные и поэтапно выполнять код строка за строкой. С отладчиком приложения могут работать медленнее, так как для отладки используются различные обработчики.
Команда Запустить без отладки запускает приложение напрямую, как если бы оно запускалось из командной строки без контекста отладки. Команда Запустить без отладки также автоматически запускает браузер и переходит по URL-адресу, указанному на вкладке Отладка свойств проекта.
Дальнейшие действия
Поздравляем с запуском вашего первого приложения Python из Visual Studio. Вы немного узнали об использовании Visual Studio в качестве интегрированной среды разработки Python!
Так как приведенные в этом руководстве инструкции довольно общие, вы, вероятно, догадались, что их можно и нужно автоматизировать. Такая автоматизация выполняется при помощи шаблонов проектов Visual Studio. Изучите краткое руководство Создание проекта Python с использованием шаблона, чтобы узнать, как создать веб-приложение, похожее на описанные в этой статье, но с меньшим количеством шагов.
Чтобы перейти к более полному учебнику по работе с Python в Visual Studio, в том числе к использованию интерактивного окна, отладки, визуализации данных и работы с Git, см. раздел Учебник. Начало работы с Python в Visual Studio.
Более подробно ознакомиться с возможностями Visual Studio можно по приведенным ниже ссылкам.
Краткое руководство. Создание функции Python в Azure с помощью Visual Studio Code
Из этой статьи вы узнаете, как создать функцию Python, которая отвечает на HTTP-запросы, используя Visual Studio Code. После тестирования кода в локальной среде его необходимо развернуть в бессерверной среде Функций Azure.
Выполнение этого краткого руководства предполагает небольшую дополнительную плату в несколько центов США в учетной записи Azure.
Существует также версия этой статьи для интерфейса командной строки.
Настройка среды
Перед началом работы убедитесь, что выполнены следующие требования:
Учетная запись Azure с активной подпиской. Создайте учетную запись бесплатно.
Версии Python, поддерживаемые Функциями Azure. Дополнительные сведения см. в разделе Как установить Python.
Расширение Python для Visual Studio Code.
Создание локального проекта
В этом разделе показано, как использовать Visual Studio Code, чтобы создать локальный проект Функций Azure на Python. Далее в этой статье вы опубликуете код функции в Azure.
Щелкните значок Azure на панели действий. Затем в области Рабочая область (локальная) нажмите кнопку + и выберите пункт Создать функцию в раскрывающемся списке. В ответ на запрос выберите вариант Создать проект.
Выберите расположение каталога для рабочей области проекта и нажмите кнопку Выбрать. Нужно либо создать новую папку, либо выбрать пустую папку для рабочей области проекта. Не выбирайте папку проекта, которая является частью рабочей области.
Введите следующие сведения по соответствующим запросам:
Используя эти сведения, Visual Studio Code создает проект функций Azure с триггером HTTP. Файлы локального проекта можно просмотреть в Explorer. Дополнительные сведения о созданных файлах см. в разделе Созданные файлы проекта.
Локальное выполнение функции
Visual Studio Code интегрируется с Azure Functions Core Tools, чтобы перед публикацией в Azure можно было запустить этот проект на локальном компьютере разработки.
Чтобы запустить функцию локально, нажмите клавишу F5 или щелкните значок воспроизведения. На панели Терминал отобразятся выходные данные из Core Tools. Ваше приложение запускается в панели Терминал. Отобразится URL-адрес конечной точки активируемой HTTP-запросом функции, которая выполняется локально.
При возникновении проблем с запуском в Windows убедитесь, что в качестве терминала по умолчанию для Visual Studio Code не используется оболочка WSL.
В поле Ввести текст запроса вы увидите значение текста запроса < "name": "Azure" >. Нажмите клавишу ВВОД, чтобы отправить это сообщение запроса в свою функцию.
При выполнении функции локально и возврате ответа в Visual Studio Code отобразится уведомление. Сведения о выполнении функции отображаются на панели Терминал.
Убедившись, что функция выполняется правильно на локальном компьютере, опубликуйте проект в Azure с помощью Visual Studio Code.
Вход в Azure
Прежде чем публиковать приложение, необходимо войти в Azure.
При появлении запроса в браузере выберите учетную запись Azure и войдите в нее с помощью учетных данных. Если вы создаете новую учетную запись, вы можете выполнить вход после ее создания.
Выполнив вход, можно закрыть новое окно браузера. Подписки, принадлежащие учетной записи Azure, отображаются на боковой панели.
Создание приложения-функции в Azure
В этом разделе показано, как создать приложение-функцию и связанные ресурсы в подписке Azure.
Щелкните значок Azure на панели действий. Затем в области Ресурсы щелкните значок + и выберите вариант Создать приложение-функцию в Azure.
Введите следующие сведения по соответствующим запросам:
prompt | Выбор |
---|---|
Выбор подписки | Выберите подписку, которую нужно использовать. Эта подсказка не отобразится, если в области Ресурсы отображается только одна подписка. |
Ввод глобально уникального имени для приложения-функции | Введите имя, допустимое в пути URL-адреса. Имя, которое вы вводите, проверяется, чтобы убедиться, что оно уникально в функциях Azure. |
Выбор стека среды выполнения | Выберите версию языка, которая запускалась локально. |
Выбор расположения для новых ресурсов | Для повышения производительности выберите регион рядом с вами. |
Расширение показывает на панели Azure: журнал действий состояние отдельных ресурсов по мере их создания в Azure.
После завершения создания в вашей подписке будут созданы приведенные ниже ресурсы Azure. Имена ресурсов основаны на имени приложения-функции.
После создания приложения-функции и применения пакета развертывания отобразится уведомление.
По умолчанию ресурсы Azure, необходимые для приложения функции, создаются на основе указанного имени приложения функции. По умолчанию они также создаются в той же новой группе ресурсов, что и приложение-функция. Если необходимо настроить имена этих ресурсов или повторно использовать существующие ресурсы, вам нужно опубликовать проект с дополнительными параметрами создания.
Развертывание проекта в Azure
Развертывание в существующем приложении-функции всегда перезаписывает содержимое этого приложения в Azure.
После завершения развертывания выберите Просмотреть выходные данные, чтобы просмотреть результаты создания и развертывания, включая созданные ресурсы Azure. Если вы пропустили уведомление, щелкните значок колокольчика в правом нижнем углу, чтобы снова просмотреть его.
Запуск функции в Azure
В поле Ввести текст запроса вы увидите значение текста запроса < "name": "Azure" >. Нажмите клавишу ВВОД, чтобы отправить это сообщение запроса в свою функцию.
При выполнении функции в Azure и возврате ответа в Visual Studio Code отобразится уведомление.
Очистка ресурсов
При переходе к следующему шагу и добавлении привязки очереди службы хранилища Azure к функции, вам потребуется сохранить все ресурсы, чтобы использовать их в будущем.
В противном случае выполните следующие действия, чтобы удалить приложение-функцию и связанные с ним ресурсы и избежать дополнительных расходов.
На вкладке Обзор выберите именованную ссылку рядом с полем Группа ресурсов.
На странице Группа ресурсов просмотрите список включенных ресурсов и убедитесь, что именно их нужно удалить.
На странице Resource group (Группа ресурсов) просмотрите список включенных ресурсов и убедитесь, что именно их требуется удалить.
Выберите Удалить группу ресурсов и следуйте инструкциям.
Удаление может занять несколько минут. После этого на несколько секунд появится уведомление. Кроме того, можно выбрать значок колокольчика в верхней части страницы, чтобы просмотреть уведомление.
Дополнительные сведения о затратах на использование Функций см. в статье Оценка затрат на план потребления.
Дальнейшие действия
С помощью Visual Studio Code вы создали приложение-функцию с простой функцией, активируемой HTTP-запросом. В следующей статье показано, как расширить эту функцию путем подключения к службе хранилища Azure. Дополнительные сведения о подключении к другим службам Azure см. в статье Подключение функций к службам Azure с помощью привязок.
Configure Python web apps for IIS
When using Internet Information Services (IIS) as a web server on a Windows computer (including Windows virtual machines on Azure), Python apps must include specific settings in their web.config files so that IIS can properly process Python code. The computer itself must also have Python installed along with any packages the web app requires.
Install Python on Windows
To run a web app, first install your required version of Python directly on the Windows host machine as described on Install Python interpreters.
Record the location of the python.exe interpreter for later steps. For convenience, you can add that location to your PATH environment variable.
Install packages
Set web.config to point to the Python interpreter
Your app’s web.config file instructs the IIS (7+) web server running on Windows about how it should handle Python requests through either HttpPlatform (recommended) or FastCGI. Visual Studio versions 2015 and earlier make these modifications automatically. When using Visual Studio 2017 and later, you must modify web.config manually.
Configure the HttpPlatform handler
The HttpPlatform module passes socket connections directly to a standalone Python process. This pass-through allows you to run any web server you like, but requires a startup script that runs a local web server. You specify the script in the element of web.config, where the processPath attribute points to the site extension’s Python interpreter and the arguments attribute points to your script and any arguments you want to provide:
Configure the FastCGI handler
FastCGI is an interface that works at the request level. IIS receives incoming connections and forwards each request to a WSGI app running in one or more persistent Python processes.
We recommend using HttpPlatform to configure your apps, as the WFastCGI project is no longer maintained.
To use FastCGI, first install and configure the wfastcgi package as described on pypi.org/project/wfastcgi/.
Next, modify your app’s web.config file to include the full paths to python.exe and wfastcgi.py in the PythonHandler key. The steps below assume that Python is installed in c:\python36-32 and that your app code is in c:\home\site\wwwroot; adjust for your paths accordingly:
Modify the PythonHandler entry in web.config so that the path matches the Python install location (see IIS Configuration Reference (iis.net) for exact details).
Set the WSGI_HANDLER entry in web.config as appropriate for the framework you’re using:
Bottle: make sure you have parentheses after app.wsgi_app as shown below. This is necessary because that object is a function (see app.py) rather than a variable:
Flask: Change the WSGI_HANDLER value to
matches the name of your project. You can find the exact identifier by looking at the from
import app statement in the runserver.py. For example, if the project is named «FlaskAzurePublishExample», the entry would appear as follows:
Django: Two changes are needed to web.config for Django projects. First, change the WSGI_HANDLER value to django.core.wsgi.get_wsgi_application() (the object is in the wsgi.py file):
Django apps only: In the Django project’s settings.py file, add your site URL domain or IP address to ALLOWED_HOSTS as shown below, replacing ‘1.2.3.4’ with your URL or IP address, of course:
Failure to add your URL to the array results in the error DisallowedHost at / Invalid HTTP_HOST header: ‘ ‘. You may need to add ‘ ‘ to ALLOWED_HOSTS.
How to create and manage Python environments in Visual Studio
A Python environment is a context in which you run Python code and includes global, virtual, and conda environments. An environment consists of an interpreter, a library (typically the Python Standard Library), and a set of installed packages. These components together determine valid language constructs and syntax, operating-system functionality that you can access, and packages you can use.
In Visual Studio on Windows, you use the Python Environments window, as described in this article, to manage environments and select one as the default for new projects. Other aspects of environments are found in the following articles:
For any given project, you can select a specific environment rather than use the default.
For details on creating and using virtual environments for Python projects, see Use virtual environments.
If you want to install packages in an environment, refer to the Packages tab reference.
To install another Python interpreter, see Install Python interpreters. In general, if you download and run an installer for a mainline Python distribution, Visual Studio detects that new installation and the environment appears in the Python Environments window and can be selected for projects.
If you’re new to Python in Visual Studio, the following articles also provide from general background:
The Python Environments window
The environments that Visual Studio knows about are displayed in the Python Environments window. To open the window, use one of the following methods:
In all these cases, the Python Environments window appears alongside Solution Explorer:
Visual Studio looks for installed global environments using the registry (following PEP 514), along with virtual environments and conda environments (see Types of environments). If you don’t see an expected environment in the list, see Manually identify an existing environment.
When you select an environment in the list, Visual Studio displays various properties and commands for that environment on the Overview tab.
For example, you can see in the image above that the interpreter’s location is C:\Python36-32. The four commands at the bottom of the Overview tab each open a command prompt with the interpreter running. For more information, see Python Environments window tab reference 2019- Overview.
For example, you can see in the image above that the interpreter’s location is C:\Program Files (x86)\Microsoft Visual Studio\Python310. The four commands at the bottom of the Overview tab each open a command prompt with the interpreter running. For more information, see Python Environments window tab reference 2022- Overview.
Use the drop-down list below the list of environments to switch to different tabs such as Packages, and IntelliSense. These tabs are also described in the Python Environments window tab reference.
Selecting an environment doesn’t change its relation to any projects. The default environment, shown in boldface in the list, is the one that Visual Studio uses for any new projects. To use a different environment with new projects, use the Make this the default environment for new projects command. Within the context of a project, you can always select a specific environment. For more information, see Select an environment for a project.
To the right of each listed environment, is a control that opens an Interactive window for that environment. (In Visual Studio 2017 15.5 and earlier, another control appears that refreshes the IntelliSense database for that environment. See Environments window tab reference for details about the database.)
When you expand the Python Environments window wide enough, you’ll get a fuller view of your environments that is more convenient to work with.
When you expand the Python Environments window wide enough, you’ll get a fuller view of your environments that is more convenient to work with.
Although Visual Studio respects the system-site-packages option, it doesn’t provide a way to change it from within Visual Studio.
What if no environments appear?
If no environments appear, it means Visual Studio failed to detect any Python installations in standard locations. For example, you might have installed Visual Studio 2017 or later but cleared all the interpreter options in the installer options for the Python workload. Similarly, you might have installed Visual Studio 2015 or earlier but didn’t install an interpreter manually (see Install Python interpreters).
If you know you have a Python interpreter on your computer but Visual Studio (any version) didn’t detect it, then use the + Custom command to specify its location manually. See the next section, Manually identify an existing environment.
Types of environments
Visual Studio can work with global, virtual, and conda environments.
Global environments
Each Python installation maintains its own global environment. For example, Python 2.7, Python 3.6, Python 3.7, Anaconda 4.4.0, and so on. See Install Python interpreters)
Each environment is composed of the specific Python interpreter, its standard library, a set of pre-installed packages, and any other packages you install while that environment is activated. Installing a package into a global environment makes it available to all projects using that environment. If the environment is located in a protected area of the file system (within c:\program files, for example), then installing packages requires administrator privileges.
Global environments are available to all projects on the computer. In Visual Studio, you select one global environment as the default, which is used for all projects unless you specifically choose a different one for a project. For more information, see Select an environment for a project.
Virtual environments
Working in a global environment is an easy way to get started. Over time, the environments become cluttered with many different packages that you’ve installed for different projects. Such clutter makes it difficult to thoroughly test your application against a specific set of packages with known versions. But, the kind of environment is exactly as above that you’d set up on a build server or web server. Conflicts can also occur when two projects require incompatible packages or different versions of the same package.
For this reason, developers often create a virtual environment for a project. A virtual environment is a subfolder in a project that contains a copy of a specific interpreter. If you activate the virtual environment, any packages you install are installed only in that environment’s subfolder. When you then run a Python program within that environment, you know that it’s running against only those specific packages.
Visual Studio provides direct support for creating a virtual environment for a project. For example, if you open a project that contains a requirements.txt, or create a project from a template that includes that file, Visual Studio prompts you automatically to create a virtual environment and install those dependencies.
At any time within an open project, you can create a new virtual environment. In Solution Explorer, expand the project node, right-click Python Environments, and choose Add environment. In Add Environment, choose Virtual environment.
Visual Studio also provides a command to generate a requirements.txt file from a virtual environment, making it easy to recreate the environment on other computers. For more information, see Use virtual environments.
Conda environments
A conda environment is one you create using the conda tool, or with integrated conda management in Visual Studio 2017 version 15.7 and higher. (Requires Anaconda or Miniconda, which are available through the Visual Studio installer, see Install Visual Studio 2017
Select Add Environment. in the Python Environments window (or from the Python toolbar), which opens the Add environment dialog box.
In the Add environment dialog, select the Conda environment tab:
Configure the following fields:
When creating a conda environment, be sure to specify at least one Python version or Python package using either environments.yml or the package list, which ensures that the environment contains a Python runtime. Otherwise, Visual Studio ignores the environment: the environment doesn’t appear anywhere the Python Environments window, isn’t be set as the current environment for a project, and isn’t available as a global environment.
If you happen to create a conda environment without a Python version, use the conda info command to see the locations of conda environment folders, then manually remove the subfolder for the environment from that location.
Select Create, and observe progress in the Output window.
The output includes with a few CLI instructions once creation is complete:
Within Visual Studio, you can activate a conda environment for a project as you would any other environment as described on Select an environment for a project.
To install more packages in the environment, use the Packages tab.
Select Add Environment. in the Python Environments window (or from the Python toolbar), which opens the Add environment dialog box.
In the Add environment dialog, select the Conda environment tab:
Configure the following fields:
When creating a conda environment, be sure to specify at least one Python version or Python package using either environments.yml or the package list, which ensures that the environment contains a Python runtime. Otherwise, Visual Studio ignores the environment: the environment doesn’t appear anywhere the Python Environments window, isn’t be set as the current environment for a project, and isn’t available as a global environment.
If you happen to create a conda environment without a Python version, use the conda info command to see the locations of conda environment folders, then manually remove the subfolder for the environment from that location.
Select Create, and observe progress in the Output window. The output includes with a few CLI instructions once creation is complete:
Within Visual Studio, you can activate a conda environment for a project as you would any other environment as described on Select an environment for a project.
To install more packages in the environment, use the Packages tab.
For best results with conda environments, use conda 4.4.8 or later (conda versions are different from Anaconda versions). You can install suitable versions of Miniconda (Visual Studio 2019 and Visual Studio 2022) and Anaconda (Visual Studio 2017) through the Visual Studio installer.
To see the conda version, where conda environments are stored, and other information, run conda info at an Anaconda command prompt (that is, a command prompt where Anaconda is in the path):
Your conda environment folders appear as follows:
Because conda environments aren’t stored with a project, they act similarly to global environments. For example, installing a new package into a conda environment makes that package available to all projects using that environment.
For Visual Studio 2017 version 15.6 and earlier, you can use conda environments by pointing to them manually as described under Manually identify an existing environment.
Visual Studio 2017 version 15.7 and later detects conda environments automatically and displays them in the Python Environments window as described in the next section.
Manually identify an existing environment
Use the following steps to identify an environment that’s installed in a non-standard location:
Select Add Environment. in the Python Environments window (or from the Python toolbar), which opens the Add environment dialog box.
In the Add environment dialog, select the Existing environment tab:
Select the Environment drop-down, then select Custom:
In the provided fields in the dialog box, enter or browse (using . ) to the path of the interpreter under Prefix path, which fills in most of the other fields.
After reviewing those values and modifying as necessary, select Add.
You can also review and modify details of the environment at any time in the Python Environments window.
In Python environment window, select the environment, and then select the Configure tab.
After making changes, select the Apply command. You can also remove the environment using the Remove command (not available for autodetected environments). For more information, see Configure tab.
Select Add Environment. in the Python Environments window (or from the Python toolbar), which opens the Add environment dialog box.
In the Add environment dialog, select the Existing environment tab:
For example, select an existing environment and the path to the existing environment.
Select the Environment drop-down, then select Custom:
.
For example, Anaconda 2021.05 in C:\Users\user\Anaconda3\python.exe
In the provided fields in the dialog box, enter or browse (using . ) to the path of the interpreter under Prefix path, which fills in most of the other fields.
After reviewing those values and modifying as necessary, select Add.
You can also review and modify details of the environment at any time in the Python Environments window.
In the Python environment window, select the environment, and then select the Configure tab.
After making changes, select the Apply command. You can also remove the environment using the Remove command (not available for autodetected environments). For more information, see Configure tab.
Fix or delete invalid environments
If Visual Studio finds registry entries for an environment, but the path to the interpreter is invalid, then the Python Environments window shows the name with a strikeout font:
To correct an environment you wish to keep, first try using its installer’s Repair process. The installers for standard Python 3.x, for example, include that option.
Modify the registry to correct an environment that doesn’t have a repair option, or to remove an invalid environment
Use the following steps to modify the registry directly. Visual Studio automatically updates thePython Environments window when you make changes to the registry.
Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Python or HKEY_CURRENT_USER\SOFTWARE\Python. For IronPython, look for IronPython instead.
Expand the node that matches the distribution, such as Python Core for CPython or ContinuumAnalytics for Anaconda. For IronPython, expand the version number node.
Inspect the values under the InstallPath node:
Источники:
- http://code.visualstudio.com/docs/python/coding-pack-python
- http://docs.microsoft.com/ru-ru/visualstudio/python/editing-python-code-in-visual-studio?view=vs-2019
- http://realpython.com/python-development-visual-studio-code/
- http://code.visualstudio.com/docs/python/tutorial-flask
- http://code.visualstudio.com/docs/python/tutorial-django
- http://docs.microsoft.com/ru-ru/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-00-installation?view=vs-2019
- http://code.visualstudio.com/docs/python/testing
- http://code.visualstudio.com/docs/python/linting
- http://docs.microsoft.com/ru-ru/visualstudio/python/managing-python-environments-in-visual-studio?view=vs-2022
- http://docs.microsoft.com/ru-RU/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-01-create-project?view=vs-2022
- http://docs.microsoft.com/ru-ru/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-00-installation?view=vs-2022
- http://docs.microsoft.com/en-us/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-02-writing-code?view=vs-2022
- http://docs.microsoft.com/ru-Ru/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-02-writing-code?view=vs-2022
- http://docs.microsoft.com/en-us/visualstudio/python/debugging-python-in-visual-studio?view=vs-2022
- http://docs.microsoft.com/ru-ru/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-02-writing-code?view=vs-2019
- http://docs.microsoft.com/ru-ru/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-04-debugging?view=vs-2022
- http://docs.microsoft.com/en-us/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-01-create-project?view=vs-2022
- http://docs.microsoft.com/ru-ru/visualstudio/python/editing-python-code-in-visual-studio?view=vs-2022
- http://marketplace.visualstudio.com/items?itemName=ms-python.python
- http://medium.com/@dmrlx/%D0%BD%D0%B0%D1%81%D1%82%D1%80%D0%BE%D0%B9%D0%BA%D0%B0-vs-code-%D0%B4%D0%BB%D1%8F-%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D1%8B-%D1%81-python-35bf237dcaeb
- http://docs.microsoft.com/ru-ru/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-04-debugging?view=vs-2019
- http://docs.microsoft.com/ru-ru/visualstudio/python/python-interactive-repl-in-visual-studio?view=vs-2022
- http://docs.microsoft.com/en-us/visualstudio/python/tutorial-working-with-python-in-visual-studio-step-02-writing-code?view=vs-2019
- http://docs.microsoft.com/en-us/visualstudio/python/editing-python-code-in-visual-studio?view=vs-2022
- http://docs.microsoft.com/ru-ru/visualstudio/ide/quickstart-python?view=vs-2022
- http://docs.microsoft.com/ru-ru/azure/azure-functions/create-first-function-vs-code-python
- http://docs.microsoft.com/ru-ru/visualstudio/python/configure-web-apps-for-iis-windows?view=vs-2022
- http://docs.microsoft.com/en-us/visualstudio/python/managing-python-environments-in-visual-studio?view=vs-2019