Пакет визуал для питона

Python

IntelliSense (Pylance), Linting, Debugging (multi-threaded, remote), Jupyter Notebooks, code formatting, refactoring, unit tests, and more.

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 extension to give you the best experience when working with Python files. 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

  • Step 1.Install a supported version of Python on your system (note: that the system install of Python on macOS is not supported).
  • Step 2.Install the Python extension for Visual Studio Code.
  • Step 3. Open or create a Python file and start coding!

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 offers support for Jupyter notebooks via the Jupyter extension to provide you a great Python notebook experience in VS Code.

  • Install the Jupyter extension.
  • Open or create a Jupyter Notebook file (.ipynb) and start coding in our Notebook Editor!

For more information you can:

  • Follow our Python tutorial with step-by-step instructions for building a simple app.
  • Check out the Python documentation on the VS Code site for general information about using the extension.
  • Check out the Jupyter Notebook documentation on the VS Code site for information about using Jupyter Notebooks in VS Code.

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:

Читайте также:  Java reflection get parent class
Command Description
Python: Select Interpreter Switch between Python interpreters, versions, and environments.
Python: Start REPL Start an interactive Python REPL using the selected interpreter in the VS Code terminal.
Python: Run Python File in Terminal Runs the active Python file in the VS Code terminal. You can also run a Python file by right-clicking on the file and selecting Run Python File in Terminal .
Python: Select Linter Switch from Pylint to Flake8 or other supported linters.
Format Document Formats code using the provided formatter in the settings.json file.
Python: Configure Tests Select a test framework and configure it to display the Test Explorer.

To see all available Python commands, open the Command Palette and type Python . For Jupyter extension commands, just type Jupyter .

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 and method extraction. Additionally, there is componentized support to enable additional refactoring, such as import sorting, through extensions including isort and Ruff.

Supported locales

The extension is available in multiple languages: de , en , es , fa , fr , it , ja , ko-kr , nl , pl , pt-br , ru , tr , zh-cn , zh-tw

Questions, issues, feature requests, and contributions

  • If you have a question about how to accomplish something with the extension, please ask on Stack Overflow
  • If you come across a problem with the extension, please file an issue
  • Contributions are always welcome! Please see our contributing guide for more details
  • Any and all feedback is appreciated and welcome!
    • If someone has already filed an issue that encompasses your feedback, please leave a 👍/👎 reaction on the issue
    • Otherwise please start a new discussion

    Источник

    Шаг 5. Установка пакетов в окружении Python

    Область применения:yesVisual StudionoVisual Studio для Mac noVisual Studio Code

    Сообщество разработчиков на Python создало тысячи полезных пакетов, которые вы можете включать в свои проекты. В Visual Studio имеется пользовательский интерфейс для управления пакетами в средах Python.

    Просмотр окружений

    1. Выберите команду меню Просмотр>Другие окна>Окружения Python. Откроется окно Окружения Python (как узел обозревателя решений), в котором представлены разные среды, доступные вам. Список содержит как окружения, установленные с помощью установщика Visual Studio, так и окружения, которые вы установили отдельно. В их число входят глобальные, виртуальные среды и среды Conda. Среда, выделенная полужирным шрифтом, — это среда, используемая по умолчанию для новых проектов. Дополнительные сведения о работе со окружениями см. в разделе Создание окружений Python и управление ими в средах Visual Studio.

    Окно

    Окно

    Примечание Используйте сочетания клавиш CTRL +K, CTRL +` , чтобы открыть окно Окружения Python из окна Обозревателя решений. Если сочетание клавиш не работает и окно «Окружения Python» отсутствует в меню, возможно, не установлена рабочая нагрузка Python. Инструкции по установке Python см. в статье Установка поддержки Python в Visual Studio в Windows.

    Если открыт проект Python, вы можете открыть окно Окружения Python из Обозревателя решений. Щелкните правой кнопкой мыши Окружения Python и выберите пункт Просмотреть все окружения Python.

    Окружения Python-2022

    Окружения Python-2019

    from math import radians import numpy as np # installed with matplotlib import matplotlib.pyplot as plt def main(): x = np.arange(0, radians(1800), radians(12)) plt.plot(x, np.cos(x), 'b') plt.show() main() 

    Неразрешенный импорт пакетов-2022

    Неразрешенный импорт пакетов

    Установка пакетов с помощью окна «Окружения Python»

    1. В окне «Окружения Python» выберите окружение по умолчанию для новых проектов Python и перейдите на вкладку Пакеты. Вы увидите список пакетов, которые в настоящее время установлены в окружении.

    Установка matplotlib в окружении-2022 на вкладке

    Установка matplotlib в окружении-2019 на вкладке

    Установка пакета matplotlib в окружении-2022

    Установка пакета matplotlib в окружении-2019

    Примечание Под названием среды может появиться небольшой индикатор выполнения, который указывает на то, что Visual Studio создает базу данных IntelliSense для нового пакета. На вкладке IntelliSense также приводятся более подробные сведения. Имейте в виду, что, пока база данных не будет готова, функции IntelliSense, такие как автозавершение и проверка синтаксиса, будут неактивны для этого пакета в редакторе.

    В Visual Studio 2017 версии 15.6 и более поздних версий используются другие (более быстрые) методы для работы с IntelliSense. На вкладке IntelliSense отображается соответствующее сообщение.

    Запуск программы

    После установки matplotlib запустите программу с отладчиком (F5) или без него (CTRL+F5), чтобы увидеть результат.

    Источник

    Разработка приложений на Python

    screenshot of python development

    Разрешите Visual Studio проанализировать ваш код и подсказать вам, какие типы и где использовать. Всплывающие подсказки, завершения и фрагменты кода, повышающие вашу производительность.

    Библиотеки

    Найдите и установите необходимые библиотеки

    Библиотеки сторонних поставщиков — самый быстрый способ решения проблемы. Используйте наши средства Pip, PyPI и поддержку виртуальной среды для управления проектами и зависимостями.

    Пакеты

    Отладка

    Отладка

    Интерактивная диагностика проблем с кодом в Windows и Linux

    Никто не в состоянии постоянно писать идеальный код, но Visual Studio может помочь в случае возникновения проблем. Визуальное пошаговое выполнение кода, просмотр или изменение состояния и взаимодействие с программой независимо от операционной системы.

    Система управления версиями

    Git и TFS без командной строки

    Управляйте проектами Git или TFS, ожидающими изменениями и ветвями с помощью Team Explorer или используйте одно из расширений для управления исходным кодом, доступных для Visual Studio.

    SourceControl

    UnitTests

    Модульные тесты

    Проверка изменений в редакторе

    Убедитесь, что код работает правильно, не выходя из Visual Studio. Просмотр, изменение, запуск и отладка модульных тестов стиля теста из окна тестирования.

    Открытый код

    Посетите нас на Github

    Инструменты Python для Visual Studio — это совершенно бесплатное расширение, разработанное и поддерживаемое корпорацией Майкрософт с помощью сообщества. Посетите нашу страницу Github для просмотра или участия в разработке PTVS.

    Источник

    Install Python support in Visual Studio

    Applies to: yesVisual Studio noVisual Studio for Mac noVisual Studio Code

    Python support is available only on Visual Studio for Windows. On Mac and Linux, Python support is available through Visual Studio Code.

    Download & install the Python workload

    1. Download and run the latest Visual Studio installer for Windows. Python support is present in the release 15.2 and later. If you have Visual Studio installed already, open Visual Studio and run the installer by selecting Tools >Get Tools and Features.

    Tip The Community edition is for individual developers, classroom learning, academic research, and open source development. For other uses, install Visual Studio Professional or Visual Studio Enterprise.

    The installer provides a list of workloads that are groups of related options for specific development areas. For Python, select the Python development workload and select Install: Screenshot of the Python development workload selected in the Visual Studio installer.

    Python installation options Description
    Python distributions Choose any combination of the available options, such as 32-bit and 64-bit variants of the Python 2, Python 3, Miniconda, Anaconda2, and Anaconda3 distributions that you plan to work with. Each includes the distribution’s interpreter, runtime, and libraries. Anaconda, specifically, is an open data science platform that includes a wide range of pre-installed packages. Visual Studio automatically detects existing Python installations. See The Python Environments window. Also, if a newer version of Python is available than what’s shown in the installer, you can install that version separately and Visual Studio will detect it.
    Cookiecutter template support Installs the Cookiecutter graphical UI to discover templates, input template options, and create projects and files. See Use the Cookiecutter extension.
    Python web support Installs tools for web development including HTML, CSS, and JavaScript editing support, along with templates for projects using the Bottle, Flask, and Django frameworks. See Python web project templates.
    Python native development tools Installs the C++ compiler and other necessary components to develop native extensions for Python. See Create a C++ extension for Python. Also install the Desktop development with C++ workload for full C++ support.

    By default, the Python workload gets installed for all users on a computer under:

    *%ProgramFiles%\Microsoft Visual Studio\\\\Common7\IDE\Extensions\Microsoft\Python* 
    *%ProgramFiles(x86)%\Microsoft Visual Studio\\\\Common7\IDE\Extensions\Microsoft\Python* 

    Test your install

    To quickly test Python support:

    1. Launch Visual Studio
    2. Press Alt+I to open the Python Interactive window and enter 2+2 . If you don’t see the output of 4, recheck your steps.

    Screenshot of testing Python through the interactive window.

    Screenshot of testing Python through the Visual Studio 2022 interactive window.

    Next steps

    Источник

Оцените статью