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

Как установить numpy в visual studio code

  • автор:

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

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

Просмотр сред

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

Python Environments window-2022

Python Environments window-2019

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

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

Python Environments-2022

Python Environments-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() 

Unresolved package import-2022

Unresolved package import

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

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

Installing matplotlib in the environment-2022 in Packages tab

Installing matplotlib in the environment-2019 in Packages tab

Installing matplotlib in the environment-2022

Installing matplotlib in the environment-2019

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

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

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

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

Не могу понять как импортировать библиотеки в vs code

Подскажите пожалуйста, суть в том что все нужные научные библиотеки уже установлены вместе с анакондой, но не могу никак импортировать библиотеки в фай. Неужели нужно каждый раз при создании проекта создавать отдельную папку с библиотеками? Есть какая-нибудь возможность указывать путь к библиотеке в самом .py файле? Спасибо за внимание.

Отслеживать

49k 17 17 золотых знаков 56 56 серебряных знаков 100 100 бронзовых знаков

задан 8 авг 2020 в 17:06

Байсункар Мирасбек Байсункар Мирасбек

11 1 1 золотой знак 1 1 серебряный знак 2 2 бронзовых знака

Установка поддержки Python в Visual Studio

Поддержка Python доступна только в Visual Studio для Windows. В Mac и Linux поддержка Python доступна через Visual Studio Code.

Необходимые компоненты

  • Visual Studio в Windows. Чтобы установить продукт, выполните действия, описанные в разделе «Установка Visual Studio».

Скачивание и установка рабочей нагрузки Python

Выполните следующие действия, чтобы скачать и установить рабочую нагрузку Python.

    Скачайте и запустите последний установщик Visual Studio для Windows. Поддержка Python доступна в выпуске 15.2 и выше. Если вы уже установили Visual Studio, откройте этот продукт и запустите установщик, выбрав Сервис>Получить средства и компоненты.

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

Screenshot of the Python development workload selected in the Visual Studio installer.

Установщик предоставляет список рабочих нагрузок, которые представляют собой группы связанных параметров для конкретных областей разработки. Для Python выберите рабочую нагрузку Разработка на Python и нажмите Установить.

Параметры установки Python Description
Дистрибутивы Python Выберите любое сочетание дистрибутива Python, с которым вы планируете работать. Распространенные варианты включают 32-разрядные и 64-разрядные варианты Python 2, Python 3, Miniconda, Anaconda 2 и Anaconda 3. Каждый параметр включает интерпретатор распространителя, среду выполнения и библиотеки. Anaconda, в частности, является открытой платформой обработки и анализа данных, которая включает широкий спектр предварительно установленных пакетов. Visual Studio автоматически определяет существующие установки Python. Дополнительные сведения см . в окне «Среды Python». Кроме того, если более новая версия Python доступна, чем версия, показанная в установщике, можно установить новую версию отдельно, а Visual Studio обнаруживает ее.
Поддержка шаблонов Cookiecutter Установите графический пользовательский интерфейс Cookiecutter для обнаружения шаблонов, параметров входных шаблонов и создания проектов и файлов. Дополнительные сведения см. в разделе «Использование расширения Cookiecutter».
Поддержка веб-приложений Python Установите средства для веб-разработки, включая поддержку редактирования HTML, CSS и JavaScript, а также шаблоны для проектов с помощью платформ Bottle, Flask и Django. Дополнительные сведения см. в шаблонах веб-проектов Python.
Встроенные средства разработки Python Установите компилятор C++ и другие необходимые компоненты для разработки собственных расширений для Python. Дополнительные сведения см. в статье «Создание расширения C++ для Python». Чтобы обеспечить полную поддержку С++, установите рабочую нагрузку Разработка классических приложений на C++.

По умолчанию рабочая нагрузка Python устанавливается для всех пользователей на компьютере:

%ProgramFiles%\Microsoft Visual Studio\> Common7\IDE\Extensions\Microsoft\Python где VS_version — 2022, а VS_edition>> — сообщество, профессиональный или корпоративный.

%ProgramFiles(x86)%\Microsoft Visual Studio\> Common7\IDE\Extensions\Microsoft\Python где VS_version — 2019 или 2017, а VS_edition>> — Community, Professional или Enterprise.

Проверка установки

Быстро проверка установку поддержки Python:

  1. Запустите Visual Studio.
  2. Выберите ALT +I, чтобы открыть интерактивное окно Python.
  3. В окне введите инструкцию 2+2 . Выходные данные 4 инструкции отображаются в окне. Если вы не видите правильные выходные данные, выполните следующие действия проверка.

Screenshot that shows a test of Python support through the interactive window.

Screenshot that shows a test of Python support through the Visual Studio 2022 interactive window.

Связанный контент

  • Шаг 1. Создание проекта Python
  • Определение существующего интерпретатора Python вручную

Installing NumPy

The only prerequisite for installing NumPy is Python itself. If you don’t have Python yet and want the simplest way to get started, we recommend you use the Anaconda Distribution — it includes Python, NumPy, and many other commonly used packages for scientific computing and data science.

NumPy can be installed with conda , with pip , with a package manager on macOS and Linux, or from source. For more detailed instructions, consult our Python and NumPy installation guide below.

CONDA

If you use conda , you can install NumPy from the defaults or conda-forge channels:

# Best practice, use an environment rather than install in the base env conda create -n my-env conda activate my-env # If you want to install from conda-forge conda config --env --add channels conda-forge # The actual install command conda install numpy

PIP

If you use pip , you can install NumPy with:

pip install numpy

Also when using pip, it’s good practice to use a virtual environment — see Reproducible Installs below for why, and this guide for details on using virtual environments.

Python and NumPy installation guide#

Installing and managing packages in Python is complicated, there are a number of alternative solutions for most tasks. This guide tries to give the reader a sense of the best (or most popular) solutions, and give clear recommendations. It focuses on users of Python, NumPy, and the PyData (or numerical computing) stack on common operating systems and hardware.

Recommendations#

We’ll start with recommendations based on the user’s experience level and operating system of interest. If you’re in between “beginning” and “advanced”, please go with “beginning” if you want to keep things simple, and with “advanced” if you want to work according to best practices that go a longer way in the future.

Beginning users#

On all of Windows, macOS, and Linux:

  • Install Anaconda (it installs all packages you need and all other tools mentioned below).
  • For writing and executing code, use notebooks in JupyterLab for exploratory and interactive computing, and Spyder or Visual Studio Code for writing scripts and packages.
  • Use Anaconda Navigator to manage your packages and start JupyterLab, Spyder, or Visual Studio Code.

Advanced users#

Conda#
  • Install Miniforge.
  • Keep the base conda environment minimal, and use one or more conda environments to install the package you need for the task or project you’re working on.
Alternative if you prefer pip/PyPI#

For users who know, from personal preference or reading about the main differences between conda and pip below, they prefer a pip/PyPI-based solution, we recommend:

  • Install Python from python.org, Homebrew, or your Linux package manager.
  • Use Poetry as the most well-maintained tool that provides a dependency resolver and environment management capabilities in a similar fashion as conda does.

Python package management#

Managing packages is a challenging problem, and, as a result, there are lots of tools. For web and general purpose Python development there’s a whole host of tools complementary with pip. For high-performance computing (HPC), Spack is worth considering. For most NumPy users though, conda and pip are the two most popular tools.

Pip & conda#

The two main tools that install Python packages are pip and conda . Their functionality partially overlaps (e.g. both can install numpy ), however, they can also work together. We’ll discuss the major differences between pip and conda here — this is important to understand if you want to manage packages effectively.

The first difference is that conda is cross-language and it can install Python, while pip is installed for a particular Python on your system and installs other packages to that same Python install only. This also means conda can install non-Python libraries and tools you may need (e.g. compilers, CUDA, HDF5), while pip can’t.

The second difference is that pip installs from the Python Packaging Index (PyPI), while conda installs from its own channels (typically “defaults” or “conda-forge”). PyPI is the largest collection of packages by far, however, all popular packages are available for conda as well.

The third difference is that conda is an integrated solution for managing packages, dependencies and environments, while with pip you may need another tool (there are many!) for dealing with environments or complex dependencies.

Reproducible installs#

As libraries get updated, results from running your code can change, or your code can break completely. It’s important to be able to reconstruct the set of packages and versions you’re using. Best practice is to:

  1. use a different environment per project you’re working on,
  2. record package names and versions using your package installer; each has its own metadata format for this:
    • Conda: conda environments and environment.yml
    • Pip: virtual environments and requirements.txt
    • Poetry: virtual environments and pyproject.toml

NumPy packages & accelerated linear algebra libraries#

NumPy doesn’t depend on any other Python packages, however, it does depend on an accelerated linear algebra library — typically Intel MKL or OpenBLAS. Users don’t have to worry about installing those (they’re automatically included in all NumPy install methods). Power users may still want to know the details, because the used BLAS can affect performance, behavior and size on disk:

  • The NumPy wheels on PyPI, which is what pip installs, are built with OpenBLAS. The OpenBLAS libraries are included in the wheel. This makes the wheel larger, and if a user installs (for example) SciPy as well, they will now have two copies of OpenBLAS on disk.
  • In the conda defaults channel, NumPy is built against Intel MKL. MKL is a separate package that will be installed in the users’ environment when they install NumPy.
  • In the conda-forge channel, NumPy is built against a dummy “BLAS” package. When a user installs NumPy from conda-forge, that BLAS package then gets installed together with the actual library — this defaults to OpenBLAS, but it can also be MKL (from the defaults channel), or even BLIS or reference BLAS.
  • The MKL package is a lot larger than OpenBLAS, it’s about 700 MB on disk while OpenBLAS is about 30 MB.
  • MKL is typically a little faster and more robust than OpenBLAS.

Besides install sizes, performance and robustness, there are two more things to consider:

  • Intel MKL is not open source. For normal use this is not a problem, but if a user needs to redistribute an application built with NumPy, this could be an issue.
  • Both MKL and OpenBLAS will use multi-threading for function calls like np.dot , with the number of threads being determined by both a build-time option and an environment variable. Often all CPU cores will be used. This is sometimes unexpected for users; NumPy itself doesn’t auto-parallelize any function calls. It typically yields better performance, but can also be harmful — for example when using another level of parallelization with Dask, scikit-learn or multiprocessing.

Troubleshooting#

If your installation fails with the message below, see Troubleshooting ImportError.

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy c-extensions failed. This error can happen for different reasons, often due to issues with your setup.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *