Как установить matplotlib visual studio
Установка matplotlib и архитектура графиков / plt 1
Среди всех ее функций особо выделяются следующие:
- Простота в использовании
- Постепенное развитие и интерактивная визуализация данных
- Выражения и текст в LaTeX
- Широкие возможности по контролю графических элементов
- Экспорт в разные форматы, включая PNG, PDF, SVG и EPS
О Matplotlib
matplotlib спроектирована с целью максимально точно воссоздать среду MATLAB в плане графического интерфейса и синтаксической формы. Этот подход оказался успешным, ведь он позволил задействовать особенности уже проверенного ПО (MATLAB), распространив библиотеку в среду технологий и науки. Более того, она включает тот объем работы по оптимизации, который был проделан за много лет. Результат — простота в использовании, что особенно важно для тех, у кого нет опыта работы в этой сфере.
Помимо простоты библиотека matplotlib также унаследовала от MATLAB интерактивность. Это значит, что специалист можно вставлять команду за командой для постепенной разработки графического представления данных. Этот режим отлично подходит для более интерактивных режимов работы с Python, таких как IPython, QtConsole и Jupyter Notebook, предоставляя среду для анализа данных, где есть все, что можно найти, например в Mathematica, IDL или MATLAB.
Гений создателей этой библиотеки в использовании уже доступных, зарекомендовавших себя инструментов из области науки. И это не ограничивается лишь режимом исполнения MATLAB, но также моделями текстового представления научных выражений и символов LaTeX. Благодаря своим возможностям по представлению научных выражений LaTeX был незаменимым элементом научных публикаций и документаций, в которых требуются такие визуальные репрезентации, как интегралы, объединения и производные. А matplotlib интегрирует этот инструмент для улучшения качества отображения.
Не стоит забывать о том, что matplotlib — это не отдельное приложение, а библиотека такого языка программирования, как Python. Поэтому она на полную использует его возможности. Matplotlib воспринимается как графическая библиотека, позволяющая программными средствами настраивать визуальные элементы, из которых состоят графики, и управлять ими. Способность запрограммировать визуальное представление позволяет управлять воспроизводимостью данных в разных средах особенно при изменениях или обновлениях.
А поскольку matplotlib — это библиотека Python, она позволяет на полную использовать потенциал остальных библиотек языка. Чаще всего работе с анализом данных matplotlib взаимодействует с набором других библиотек, таких как NumPy и pandas, но можно добавлять и другие.
Наконец, графическое представление из этой библиотеки можно экспортировать в самые распространенные графические форматы (PNG и SVG) и затем использовать в других приложениях, документах, в сети и так далее.
Установка
Есть много вариантов установки matplotlib. Если это дистрибутив пакетов, такой как Anaconda или Enthought Canopy, то процесс очень простой. Например, используя пакетный менеджер conda , достаточно ввести следующее:
Если его нужно установить прямо, то команды зависят от операционной системы
В системах Debian-Ubuntu:
В macOS или Windows нужно использовать pip
IPython и IPython QtConsole
Для знакомства со всеми инструментами мира Python часто используют IPython из терминала или QtConsole. Все благодаря тому, что IPython позволяет использовать интерактивность улучшенного терминала и интегрировать графику прямо в консоль.
Для запуска сессии IPython нужно использовать следующую команду:
Если же используется Jupyter QtConsole с возможностью отображения графики вместе с командами, то нужна эта:
На экране тут же отобразится новое окно с запущенной сессией IPython.
Однако ничто не мешает использовать стандартную сессию Python. Все примеры дальше будут работать и в таком случае.
Архитектура matplotlib
Одна из основных задач, которую выполняет matplotlib — предоставление набора функций и инструментов для представления и управления Figure (так называется основной объект) вместе со всеми внутренними объектами, из которого он состоит. Но в matplotlib есть также инструменты для обработки событий и, например, анимации. Благодаря им эта библиотека способна создавать интерактивные графики на основе событий по нажатию кнопки или движению мыши.
Архитектура matplotlib логически разделена на три слоя, расположенных на трех уровнях. Коммуникация непрямая — каждый слой может взаимодействовать только с тем, что расположен под ним, но не над.
- Слой сценария
- Художественный слой
- Слой бэкенда
Слой бэкенда
Слой Backend является нижним на диаграмме с архитектурой всей библиотеки. Он содержит все API и набор классов, отвечающих за реализацию графических элементов на низком уровне.
- FigureCanvas — это объект, олицетворяющий область рисования.
- Renderer — объект, который рисует по FigureCanvas .
- Event — объект, обрабатывающий ввод от пользователя (события с клавиатуры и мыши)
Художественный слой
Средним слоем выступает художественный ( artist ). Все элементы, составляющие график, такие как название, метки осей, маркеры и так далее, являются экземплярами этого объекта. Каждый из них играет свою роль в иерархической структуре.
Есть два художественных класса: примитивный и составной.
- Примитивный — это объекты, которые представляют собой базовые элементы для формирования графического представления графика, например, Line2D, или геометрические фигуры, такие как прямоугольник круг или даже текст.
- Составные — объекты, состоящие из нескольких базовых (примитивных). Это оси, шкалы и диаграммы.
На этом уровне часто приходится иметь дело с объектами, занимающими высокое положение в иерархии: график, система координат, оси. Поэтому важно полностью понимать, какую роль они играют. Следующее изображение показывает три основных художественных (составных объекта), которые часто используются на этом уровне.
- Figure — объект, занимающий верхнюю позицию в иерархии. Он соответствует всему графическому представлению и может содержать много систем координат.
- Axes — это тот самый график. Каждая система координат принадлежит только одному объекту Figure и имеет два объекта Axis (или три, если речь идет о трехмерном графике). Другие объекты, такие как название, метки x и y , принадлежат отдельно осям.
- Axis учитывает числовые значения в системе координат, определяет пределы и управляет обозначениями на осях, а также соответствующим каждому из них текстом. Положение шкал определяется объектом Locator , а внешний вид — Formatter .
Слой сценария (pyplot)
Художественные классы и связанные с ними функции (API matplotlib) подходят всем разработчикам, особенно тем, кто работает с серверами веб-приложений или разрабатывает графические интерфейсы. Но для вычислений, в частности для анализа и визуализации данных, лучше всего подходит слой сценария. Он включает интерфейс pyplot .
pylab и pyplot
Существуют две библиотеки: pylab и pyplot . Но в чем между ними разница? Pylab — это модуль, устанавливаемый вместе с matplotlib, а pyplot — внутренний модуль matplotlib. На оба часто ссылаются.
Pylab объединяет функциональность pyplot с возможностями NumPy в одном пространстве имен, поэтому отдельно импортировать NumPy не нужно. Более того, при импорте pylab функции из pyplot и NumPy можно вызывать без ссылки на модуль (пространство имен), что похоже на MATLAB.
Пакет pyplot предлагает классический интерфейс Python для программирования, имеет собственное пространство имеет и требует отдельного импорта NumPy. В последующих материалах используется этот подход. Его же применяет большая часть программистов на Python.
Installing¶
There are many different ways to install matplotlib, and the best way depends on what operating system you are using, what you already have installed, and how you want to use it. To avoid wading through all the details (and potential complications) on this page, there are several convenient options.
Installing pre-built packages¶
Most platforms : scientific Python distributions¶
Linux : using your package manager¶
If you are on Linux, you might prefer to use your package manager. matplotlib is packaged for almost every major Linux distribution.
- Debian / Ubuntu : sudo apt-get install python-matplotlib
- Fedora / Redhat : sudo yum install python-matplotlib
Mac OSX : using pip¶
If you are on Mac OSX you can probably install matplotlib binaries using the standard Python installation program pip. See Installing OSX binary wheels .
Windows¶
For standard Python installations you will also need to install compatible versions of setuptools, numpy, python-dateutil, pytz, pyparsing, and cycler in addition to matplotlib.
For Python 3.5 the Visual C++ Redistributable for Visual Studio 2015 needs to be installed. In case Python 2.7 to 3.4 are not installed for all users (not the default), the Microsoft Visual C++ 2008 ( 64 bit or 32 bit for Python 2.7 to 3.2) or Microsoft Visual C++ 2010 ( 64 bit or 32 bit for Python 3.3 and 3.4) redistributable packages need to be installed.
Matplotlib depends on Pillow for reading and saving JPEG, BMP, and TIFF image files. Matplotlib requires MiKTeX and GhostScript for rendering text with LaTeX. FFmpeg, avconv, mencoder, or ImageMagick are required for the animation module.
The following backends should work out of the box: agg, tkagg, ps, pdf and svg. For other backends you may need to install pycairo, PyQt4, PyQt5, PySide, wxPython, PyGTK, Tornado, or GhostScript.
TkAgg is probably the best backend for interactive use from the standard Python shell or IPython. It is enabled as the default backend for the official binaries. GTK3 is not supported on Windows.
The Windows installers ( *.exe ) and wheels ( *.whl ) on the PyPI download page do not contain test data or example code. If you want to try the many demos that come in the matplotlib source distribution, download the *.tar.gz file and look in the examples subdirectory. To run the test suite, copy the libmatplotlibtests and libmpl_toolkitstests directories from the source distribution to sys.prefixLibsite-packagesmatplotlib and sys.prefixLibsite-packagesmpl_toolkits respectively, and install nose, mock, Pillow, MiKTeX, GhostScript, ffmpeg, avconv, mencoder, ImageMagick, and Inkscape.
Installing from source¶
If you are interested in contributing to matplotlib development, running the latest source code, or just like to build everything yourself, it is not difficult to build matplotlib from source. Grab the latest tar.gz release file from the PyPI files page, or if you want to develop matplotlib or just need the latest bugfixed version, grab the latest git version Source install from git .
The standard environment variables CC , CXX , PKG_CONFIG are respected. This means you can set them if your toolchain is prefixed. This may be used for cross compiling.
Once you have satisfied the requirements detailed below (mainly python, numpy, libpng and freetype), you can build matplotlib:
We provide a setup.cfg file that goes with setup.py which you can use to customize the build process. For example, which default backend to use, whether some of the optional libraries that matplotlib ships with are installed, and so on. This file will be particularly useful to those packaging matplotlib.
If you have installed prerequisites to nonstandard places and need to inform matplotlib where they are, edit setupext.py and add the base dirs to the basedir dictionary entry for your sys.platform . e.g., if the header to some required library is in /some/path/include/someheader.h , put /some/path in the basedir list for your platform.
Build requirements¶
Required Dependencies¶
Optional GUI framework¶
These are optional packages which you may want to install to use matplotlib with a user interface toolkit. See What is a backend? for more details on the optional matplotlib backends and the capabilities they provide.
tk 8.3 or later The TCL/Tk widgets library used by the TkAgg backend pyqt 4.0 or later The Qt4 widgets library python wrappers for the Qt4Agg backend pygtk 2.4 or later The python wrappers for the GTK widgets library for use with the GTK or GTKAgg backend wxpython 2.8 or later The python wrappers for the wx widgets library for use with the WX or WXAgg backend
Optional external programs¶
Optional dependencies¶
Required libraries that ship with matplotlib¶
Building on Linux¶
It is easiest to use your system package manager to install the dependencies.
If you are on Debian/Ubuntu, you can get all the dependencies required to build matplotlib with:
If you are on Fedora/RedHat, you can get all the dependencies required to build matplotlib by first installing yum-builddep and then running:
This does not build matplotlib, but it does get the install the build dependencies, which will make building from source easier.
Building on OSX¶
The build situation on OSX is complicated by the various places one can get the libpng and freetype requirements (darwinports, fink, /usr/X11R6) and the different architectures (e.g., x86, ppc, universal) and the different OSX version (e.g., 10.4 and 10.5). We recommend that you build the way we do for the OSX release: get the source from the tarball or the git repository and follow the instruction in README.osx .
Building on Windows¶
Since there is no canonical Windows package manager the build methods for freetype, zlib, libpng, tcl, & tk source code are documented as a build script at matplotlib-winbuild.
The text was updated successfully, but these errors were encountered:
SarcasticWatermelon commented Feb 1, 2019
Hi @SarcasticWatermelon,
do you get the same result by just going to the console an use:
pip install matplotlib
Be sure you have the right version of pip installed (if you have different python versions (2 & 3) installed.Hope it helps,
Maurice
I think it is an error on my part. I am working on this on a school computer, so therefore it will not allow me to install things. I will try this on my home computer to see if this works and get back to you with any further issues in the future. Thanks for your help, though!
kraigb commented Feb 1, 2019
Yes, if you don’t have admin privs on a computer, then sudo elevation won’t work. In that case you need to use a virtual environment instead, in which you can install anything. I’ll make a note about that in the documentation.
Сообщество разработчиков на Python создало тысячи полезных пакетов, которые вы можете включать в свои проекты. В Visual Studio имеется пользовательский интерфейс для управления пакетами в средах Python.
Просмотр окружений
Выберите команду меню Просмотр > Другие окна > Окружения Python. Откроется окно Окружения Python (как узел обозревателя решений), в котором представлены разные среды, доступные вам. Список содержит как окружения, установленные с помощью установщика Visual Studio, так и окружения, которые вы установили отдельно. В их число входят глобальные, виртуальные среды и среды Conda. Среда, выделенная полужирным шрифтом, — это среда, используемая по умолчанию для новых проектов. Дополнительные сведения о работе со окружениями см. в разделе Создание окружений Python и управление ими в средах Visual Studio.
Используйте сочетания клавиш CTRL +K, CTRL +` , чтобы открыть окно Окружения Python из окна Обозревателя решений. Если сочетание клавиш не работает и окно "Окружения Python" отсутствует в меню, возможно, не установлена рабочая нагрузка Python. Инструкции по установке Python см. в статье Установка поддержки Python в Visual Studio в Windows.
Если открыт проект Python, вы можете открыть окно Окружения Python из Обозревателя решений. Щелкните правой кнопкой мыши Окружения Python и выберите пункт Просмотреть все окружения Python.
Теперь создайте проект, выбрав пункт меню Файл > Создать > Проект, а затем выбрав шаблон Приложение Python.
В появившийся файл кода вставьте приведенный ниже код, который строит косинусоиду, как в предыдущих шагах учебника, но теперь в виде графика. Можно также использовать ранее созданный проект и заменить код.
В окне редактора наведите указатель мыши на инструкции импорта numpy и matplotlib . Вы заметите, что они не разрешены. Чтобы разрешить инструкции импорта, установите пакеты в глобальное окружение по умолчанию.
Если в окне редактора навести указатель мыши на операторы импорта numpy и matplotlib , вы заметите, что они не разрешены. Это связано с тем, что пакеты не были установлены в глобальном окружении по умолчанию.
Например, щелкните ссылку Открыть интерактивное окно, и в Visual Studio откроется интерактивное окно для этого окружения.
На вкладке Пакеты в окне "Окружения Python" указаны все пакеты, установленные в настоящий момент в окружении.
Установка пакетов с помощью окна "Окружения Python"
В окне "Окружения Python" выберите окружение по умолчанию для новых проектов Python и перейдите на вкладку Пакеты. Вы увидите список пакетов, которые в настоящее время установлены в окружении.
Установите пакет matplotlib , введя его имя в поле поиска, а затем выбрав параметр Выполнить команду "pip install matplotlib" . При выполнении этой команды будут установлены пакет matplotlib , а также все пакеты, от которых он зависит (в данном случае — numpy ).
Выберите вкладку Пакеты.
Согласитесь на повышение прав, если появится соответствующий запрос.
Установленный пакет появится в окне Окружения Python. Если щелкнуть знак X справа от пакета, он будет удален.
Введите matplotlib в поле поиска для установки matplotlib .
Выберите вариант Выполнить команду: pip install matplotlib. Будет установлен пакет matplotlib , а также все пакеты, от которых он зависит (в данном случае — numpy ).
Согласитесь на повышение прав, если появится соответствующий запрос.
Установленный пакет появится в окне Окружения Python. Если щелкнуть знак X справа от пакета, он будет удален.
Под названием среды может появиться небольшой индикатор выполнения, который указывает на то, что Visual Studio создает базу данных IntelliSense для нового пакета. На вкладке IntelliSense также приводятся более подробные сведения. Имейте в виду, что, пока база данных не будет готова, функции IntelliSense, такие как автозавершение и проверка синтаксиса, будут неактивны для этого пакета в редакторе.
Запуск программы
После установки matplotlib запустите программу с отладчиком (F5) или без него (CTRL+F5), чтобы увидеть результат.
Интерактивное окно Visual Studio в режиме IPython предоставляет удобную интерактивную среду разработки с широкими возможностями, в том числе функцией интерактивных параллельных вычислений. В этой статье описано использование IPython в интерактивном окне Visual Studio, где также доступны все стандартные функции интерактивного окна.
Для работы с этим пошаговым руководством требуется установить IPython numpy и matplotlib. Если вы используете Anaconda, эти библиотеки уже установлены. В оставшейся части этого пошагового руководства предполагается, что вы используете Anaconda.
IronPython не поддерживает IPython, хотя его можно выбрать в форме параметров интерактивной работы. Дополнительные сведения см. в запросе функции.
Откройте Visual Studio, переключитесь в окно Окружения Python (Вид > Другие окна > Окружения Python) и выберите среду Anaconda.
Изучите вкладку Пакеты (Conda) (которая может отображаться как pip или Пакеты) для этой среды, чтобы убедиться, что ipython и matplotlib указаны. Если нет, установите их с помощью этой же вкладки. (См. раздел Вкладка "Пакеты" окна "Окружения Python".)
Откройте вкладку Обзор и выберите Использовать интерактивный режим IPython. (В Visual Studio 2015 выберите Настройка интерактивных параметров, чтобы открыть диалоговое окно Параметры, укажите значение IPython для параметра Интерактивный режим и нажмите кнопку ОК.)
Выберите Открыть интерактивное окно, чтобы открыть интерактивное окно в режиме IPython. Если вы только что установили интерактивный режим, может потребоваться сброс установок окна. Кроме того, может потребоваться нажать клавишу ВВОД, если отображается только приглашение ">>>", чтобы получить приглашение как в [2] .
Введите следующий код:
После ввода последней строки прямо в этом же окне вы увидите график (размер которого при желании можно менять, перетаскивая его за нижний правый угол).
Чтобы просмотреть график за пределами интерактивного окна, запустите код обычным образом, используя команду Отладка > Запуск без отладки.
IPython имеет множество других полезных функций, таких как экранирование символов для системной оболочки, подстановка переменных, запись вывода и т. д. Дополнительные сведения см. в документации по IPython.
The Python developer community has produced thousands of useful packages that you can incorporate into your own projects. Visual Studio provides a UI to manage packages in your Python environments.
View environments
Select the View > Other Windows > Python Environments menu command. The Python Environments window opens as a peer to Solution Explorer and shows the different environments available to you. The list shows both environments that you installed using the Visual Studio installer and environments you installed separately. That includes global, virtual, and conda environments. The environment in bold is the default environment that's used for new projects. For more information about working with environments, see How to create and manage Python environments in Visual Studio environments.
You can also use the Ctrl+K, Ctrl+` keyboard shortcut to open the Python Environments window from the Solution Explorer window. If the shortcut doesn't work and you can't find the Python Environments window in the menu, it's possible that you haven't installed the Python workload. See How to install Python support in Visual Studio on Windows for guidance about how to install Python.
With a Python project open, you can open the Python Environments window from Solution Explorer. Right-click Python Environments and select View All Python Environments.
Now, create a new project with File > New > Project, selecting the Python Application template.
In the code file that appears, paste the following code, which creates a cosine wave like the previous tutorial steps, only this time plotted graphically. You can also use the project you previously created and replace the code.
In the editor window, hover over the numpy and matplotlib import statements. You'll notice that they aren't resolved. To resolve the import statements, install the packages to the default global environment.
When you look at the editor window, notice that when you hover over the numpy and matplotlib import statements that they aren't resolved. The reason is the packages haven't been installed to the default global environment.
For example, select Open interactive window and an Interactive window for that specific environment appears in Visual Studio.
The Packages tab in the Python Environments window lists all packages that are currently installed in the environment.
Install packages using the Python Environments window
From the Python Environments window, select the default environment for new Python projects and choose the Packages tab. You'll then see a list of packages that are currently installed in the environment.
Install matplotlib by entering its name into the search field and then selecting the Run command: pip install matplotlib option. Running the command will install matplotlib , and any packages it depends on (in this case that includes numpy ).
Choose the Packages tab.
Consent to elevation if prompted to do so.
After the package is installed, it appears in the Python Environments window. The X to the right of the package uninstalls it.
Enter matplotlib into the search field to install matplotlib .
Select the Run command: pip install matplotlib option. This option installs matplotlib , and any packages it depends on (in this case, that includes numpy ).
Consent to elevation if prompted to do so.
After the package installs, it appears in the Python Environments window. The X to the right of the package uninstalls it.
A small progress bar might appear underneath the environment to indicate that Visual Studio is building its IntelliSense database for the newly-installed package. The IntelliSense tab also shows more detailed information. Be aware that until that database is complete, IntelliSense features like auto-completion and syntax checking won't be active in the editor for that package.
Visual Studio 2017 version 15.6 and later uses a different and faster method for working with IntelliSense, and displays a message to that effect on the IntelliSense tab.
Run the program
Now that matplotlib is installed, run the program with (F5) or without the debugger (Ctrl+F5) to see the output:
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:
- Visual Studio Code
- Visual Studio Code extensions:
- Python
- Pylance
- Live Share
- Gather
- jupyter
- numpy
- sklearn
- pandas
- Matplotlib
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.
- Verify your Python installation by opening a cmd prompt and running the following code python --version . If the installation was successful, the output window shows the version of Python that you just installed.
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.
- Install the Pylance extension from the Visual Studio marketplace.
- Open a Python (.py) file and the Pylance extension will activate.
- Select Yes when prompted to make Pylance the default language server. This will update your preferences, which you can also do manually by adding "python.languageServer": "Pylance" to your settings.json file using the text editor.
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.
-
and install the Visual Studio Live Share extension from the Visual Studio marketplace.
- Follow the guidance in the documentation about How-to: Collaborate using Visual Studio Code
- Open VS Code
- Within VS Code, open the Command Palette (ctrl+shift+p)
- Select Python: Select Interpreter
- Select the interpreter that you installed or that was installed by the Coding Pack
- Install the Pylance extension and set it as the default language server as described in the section above.
- Open VS Code
- If a terminal is not already opened, select Terminal > New Terminal from the main toolbar
- Once the terminal has opened, enter the following command: Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
- The folder with the Python interpreter and associated Python packages will be removed, including any user installed packages.
- The folder will be removed from the PATH environment variable.
- Any settings modified by the installation process will be reset.
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.
Читайте также: