Anaconda install package windows

Anaconda.org hosts hundreds of useful Python packages for a wide variety of applications. You do not need to be logged in—or even have an Anaconda.org account—to search for public packages and install them. You do need to be logged in, however, to access authenticated packages, and you’ll need a token to access other users’ private packages.

Searching for public packages

Use the search box at the top of the page to locate packages uploaded to Anaconda.org.

Packages that match or partially match your query display when you execute a search. To see more information, click the package name.

Refining your search results

You can filter search results using three filter controls:

  • Type: All, conda only, standard Python only, or standard R only

  • Access: All, Public, Private (only available if you are logged in and have specific permissions), or Authenticated (only available if you are logged in)

  • Platform: All, source, linux-32, linux-64, linux-aarch64, linux-armv61, linux-armv71, linux-ppc641e, linux-s390x, noarch, osx-32, osx-64, win-32, or win-64

Viewing package information

Each official package page on Anaconda.org provides valuable information about the package, such as its version, license, home webpage, documentation (if available), number of downloads, and the last time the package was updated.

You can also find commands on this page to assist you with installing the package in your environment.

You can install packages using Anaconda Navigator, Anaconda’s graphical user interface that is built on top of conda. Advanced users may prefer using Anaconda Prompt (Terminal on macOS/Linux).

Using Navigator

Navigator is automatically installed when you install Anaconda. Miniconda users can obtain Navigator by running conda install anaconda-navigator.

To install a package into its own environment:

  1. Open Anaconda Navigator.
  2. Click Connect, then click SIGN IN beside Anaconda.org.
  3. Select Environments from the left-hand navigation, then look for your package by name using the Search Packages field. Filter packages further using the dropdown above the Name column.
  4. Select the checkbox of the package you want to install, then click the Apply.

Using conda in Anaconda Prompt (Terminal on macOS/Linux)

To install a package into its own environment:

  1. Locate a package on Anaconda.org that you want to install, then click on the package name.
  2. A detail page displays specific installation instructions for the current operating system. Copy and paste the full command into your terminal window.

For example, the command could be structured as:

Note

There are many options available for the commands described
on this page. For details, see commands.

Searching for packages#

Use the terminal for the following steps.

To see if a specific package, such as SciPy, is available for
installation:

To see if a specific package, such as SciPy, is available for
installation from Anaconda.org:

conda search --override-channels --channel defaults scipy

To see if a specific package, such as iminuit, exists in a
specific channel, such as http://conda.anaconda.org/mutirri,
and is available for installation:

conda search --override-channels --channel http://conda.anaconda.org/mutirri iminuit

Installing packages#

Use the terminal for the following steps.

To install a specific package such as SciPy into an existing
environment «myenv»:

conda install --name myenv scipy

If you do not specify the environment name, which in this
example is done by --name myenv, the package installs
into the current environment:

To install a specific version of a package such as SciPy:

conda install scipy=0.15.0

To install multiple packages at once, such as SciPy and cURL:

Note

It is best to install all packages at once, so that all of
the dependencies are installed at the same time.

To install multiple packages at once and specify the version of
the package:

conda install scipy=0.15.0 curl=7.26.0

To install a package for a specific Python version:

conda install scipy=0.15.0 curl=7.26.0 -n py34_env

If you want to use a specific Python version, it is best to use
an environment with that version. For more information,
see Troubleshooting.

Installing similar packages#

Installing packages that have similar filenames and serve similar
purposes may return unexpected results. The package last installed
will likely determine the outcome, which may be undesirable.
If the two packages have different names, or if you’re building
variants of packages and need to line up other software in the stack,
we recommend using Mutex metapackages.

Installing packages from Anaconda.org#

Packages that are not available using conda install can be
obtained from Anaconda.org, a package management service for
both public and private package repositories. Anaconda.org
is an Anaconda product, just like Anaconda and Miniconda.

To install a package from Anaconda.org:

  1. In a browser, go to http://anaconda.org.

  2. To find the package named bottleneck, type bottleneck
    in the top-left box named Search Packages.

  3. Find the package that you want and click it to go to the
    detail page.

    The detail page displays the name of the channel. In this
    example it is the «pandas» channel.

  4. Now that you know the channel name, use the conda install
    command to install the package. In your terminal window, run:

    conda install -c pandas bottleneck
    

    This command tells conda to install the bottleneck package
    from the pandas channel on Anaconda.org.

  5. To check that the package is installed, in your terminal window, run:

    A list of packages appears, including bottleneck.

Note

For information on installing packages from multiple
channels, see Managing channels.

Installing non-conda packages#

If a package is not available from conda or Anaconda.org, you may be able to
find and install the package via conda-forge or with another package manager
like pip.

Pip packages do not have all the features of conda packages and we recommend
first trying to install any package with conda. If the package is unavailable
through conda, try finding and installing it with
conda-forge.

If you still cannot install the package, you can try
installing it with pip. The differences between pip and
conda packages cause certain unavoidable limits in compatibility but conda
works hard to be as compatible with pip as possible.

Note

Both pip and conda are included in Anaconda and Miniconda, so you do not
need to install them separately.

Conda environments replace virtualenv, so there is no need to activate a
virtualenv before using pip.

It is possible to have pip installed outside a conda environment or inside a
conda environment.

To gain the benefits of conda integration, be sure to install pip inside the
currently active conda environment and then install packages with that
instance of pip. The command conda list shows packages installed this way,
with a label showing that they were installed with pip.

You can install pip in the current conda environment with the command
conda install pip, as discussed in Using pip in an environment.

If there are instances of pip installed both inside and outside the current
conda environment, the instance of pip installed inside the current conda
environment is used.

To install a non-conda package:

  1. Activate the environment where you want to put the program:

    • In your terminal window, run conda activate myenv.

  2. To use pip to install a program such as See, in your terminal window, run:

  3. To verify the package was installed, in your terminal window, run:

    If the package is not shown, install pip as described in Using pip in an environment
    and try these commands again.

Installing commercial packages#

Installing a commercial package such as IOPro is the same as
installing any other package. In your terminal window, run:

conda install --name myenv iopro

This command installs a free trial of one of Anaconda’s
commercial packages called IOPro, which can speed up your
Python processing. Except for academic use, this free trial
expires after 30 days.

Viewing a list of installed packages#

Use the terminal for the following steps.

To list all of the packages in the active environment:

To list all of the packages in a deactivated environment:

Listing package dependencies#

To find what packages are depending on a specific package in
your environment, there is not one specific conda command.
It requires a series of steps:

  1. List the dependencies that a specific package requires to run:
    conda search package_name --info

  2. Find your installation’s package cache directory:
    conda info

  3. Find package dependencies. By default, Anaconda/Miniconda stores packages in ~/anaconda/pkgs/ (or ~/opt/pkgs/ on macOS Catalina).
    Each package has an index.json file which lists the package’s dependencies.
    This file resides in ~anaconda/pkgs/package_name/info/index.json.

  4. Now you can find what packages depend on a specific package. Use grep to search all index.json files
    as follows: grep package_name ~/anaconda/pkgs/*/info/index.json

The result will be the full package path and version of anything containing the <package_name>.

Example:
grep numpy ~/anaconda3/pkgs/*/info/index.json

Output from the above command:

/Users/testuser/anaconda3/pkgs/anaconda-4.3.0-np111py36_0/info/index.json: numpy 1.11.3 py36_0
/Users/testuser/anaconda3/pkgs/anaconda-4.3.0-np111py36_0/info/index.json: numpydoc 0.6.0 py36_0
/Users/testuser/anaconda3/pkgs/anaconda-4.3.0-np111py36_0/info/index.json: numpy 1.11.3 py36_0

Note this also returned “numpydoc” as it contains the string “numpy”. To get a more specific result
set you can add < and >.

Updating packages#

Use conda update command to check to see if a new update is
available. If conda tells you an update is available, you can
then choose whether or not to install it.

Use the terminal for the following steps.

  • To update a specific package:

  • To update Python:

  • To update conda itself:

Note

Conda updates to the highest version in its series, so
Python 3.9 updates to the highest available in the 3.x series.

To update the Anaconda metapackage:

conda update conda
conda update anaconda

Regardless of what package you are updating, conda compares
versions and then reports what is available to install. If no
updates are available, conda reports «All requested packages are
already installed.»

If a newer version of your package is available and you wish to
update it, type y to update:

Preventing packages from updating (pinning)#

Pinning a package specification in an environment prevents
packages listed in the pinned file from being updated.

In the environment’s conda-meta directory, add a file
named pinned that includes a list of the packages that you
do not want updated.

EXAMPLE: The file below forces NumPy to stay on the 1.7 series,
which is any version that starts with 1.7. This also forces SciPy to
stay at exactly version 0.14.2:

numpy 1.7.*
scipy ==0.14.2

With this pinned file, conda update numpy keeps NumPy at
1.7.1, and conda install scipy=0.15.0 causes an error.

Use the --no-pin flag to override the update restriction on
a package. In the terminal, run:

conda update numpy --no-pin

Because the pinned specs are included with each conda
install, subsequent conda update commands without
--no-pin will revert NumPy back to the 1.7 series.

Adding default packages to new environments automatically#

To automatically add default packages to each new environment that you create:

  1. Open a terminal window and run:
    conda config --add create_default_packages PACKAGENAME1 PACKAGENAME2

  2. Now, you can create new environments and the default packages will be installed in all of them.

You can also edit the .condarc file with a list of packages to create
by default.

You can override this option at the command prompt with the --no-default-packages flag.

Removing packages#

Use the terminal for the following steps.

  • To remove a package such as SciPy in an environment such as
    myenv:

    conda remove -n myenv scipy
    
  • To remove a package such as SciPy in the current environment:

  • To remove multiple packages at once, such as SciPy and cURL:

  • To confirm that a package has been removed:

Last Updated :
17 Jan, 2023

Let’s see some methods that can be used to install packages in the Anaconda environment. There are many ways one can add pre-built packages to an anaconda environment. So, let’s see how to direct the path in the anaconda and install them. 

Add packages to the Anaconda environment using the navigator

Step 1: Open your Anaconda navigator

Step 2: 

  • Go to the Environment tab.
  • Search your package in the upper right search bar.
  • Check the package you want to install.

Step 3: Here, you can click on apply to install or update your packages.

Add packages to the Anaconda environment using the pip command

**Take note that using pip in the anaconda environment may not work in your device. If such a case occurs, you can flawlessly use the conda command. 

  1. Open Anaconda Command prompt as administrator
  2. Use cd\ to come out of the set directory or path.
  3. Run pip install command. 
pip install numpy
pip install scikit-learn

Add packages to the Anaconda environment using git 

  1. Download git files
  2. Clone or download git hub files in some directory.
  3. Open Anaconda Command prompt as administrator.
  4. Use cd C:\Users\… to locate the downloaded site.
  5. Then run pip install setup.py.

Add packages to the Anaconda environment wheel 

  1. Download the wheel package.
  2. Download binary files or .whl files from an authentic website.
  3. Open Anaconda Command prompt as administrator.
  4. Use cd C:\Users\… to locate the downloaded site.
  5. Then run pip install ___.whl

Add packages to the Anaconda environment Conda forge Command 

This type of installation will guarantee that package will be downloaded to the system. Because this type of installation resolves environments, package-package conflicts, etc.  

  1. Self Upgrade related packages to the downloading package.
  2. Open Anaconda Command prompt as administrator.
  3. Then run conda install -c conda-forge ____
conda install -c conda-forge opencv 

Цель данного материала — познакомить вас с Anaconda — инструментом, который поможет вам в программировании на Python и не только. Он пригодится, чтобы не запутаться в версиях установленных библиотек, а также с лёгкостью поможет установить необходимые для курса пакеты.

Это лишь один из общепринятых инструментов для аналитики, другие мы затронем позже или же в других курсах, посвящённых статистике.

Anacondaнаиболее известна как дистрибутив Python со встроенным в него пакетным менеджером conda. Она позволяет изолировать окружение проекта от системной версии Python, который критически необходим для работы системы. Использование sudo pip считается плохой практикой. Также conda позволяет без проблем переносить окружение с одной машины на другую. Кроме того, если вы что-то сломаете, то с Anaconda вы всегда сможете откатиться на более старую версию окружения. Конечно, если вы позаботитесь о регулярных бэкапах. С системной версией Python это гораздо сложнее и может потребовать переустановки системы.

Въедливый читатель скажет, что вместо Anaconda можно использовать virtualenv или docker. Тем не менее, docker это чаще всего overkill для простых проектов. Его сложно настраивать, он работает относительно медленно и требует sudo-прав. Связка pip + virtualenv хорошо работает для Python-only проектов, но вам также может быть придётся также работать с R. Кроме того, conda во многом аналогична пакетному менеджеру внутри операционной системы и позволяет локально без sudo-прав, которых в облаке у вас почти никогда нет, установить gcc, бразуер, альтернативный shell и многое другое для 100+ языков. С более подробным сравнением Anaconda с альтернативными инструментами вы можете ознакомиться по ссылке.

Мы установим Anaconda и настроим с её помощью комфортное окружение для работы над учебными курсами.

Замечание: Anaconda можно поставить и под Windows, на официальном сайте есть инструкция. Тем не менее, мы не берёмся гарантировать, что всё заработает. Портирование кода под Windows это долго и дорого, потому большая часть библиотек по анализу данных и машинному обучению доступны только под Linux.

Установка Anaconda

Скачайте последнюю версию Anaconda под свою ОС с официального сайта. Запустите установочный файл и следуйте инструкциям. Не меняйте дефолтные параметры без уважительной причины.
После установки перезагрузите терминал, например, с помощью команды exec bash. Если всё прошло успешно, то ячейка ниже должна отработать без ошибок:

Создание conda environment

Заводить отдельный environment для каждого проекта — правило хорошего тона. Устанавливать всё в корневой envirnonment — прямой путь в отдельный круг ада, на который вы обрекаете себя в будущем. Кроме того, что это противоречит философии conda, — возможности сосуществования несовместимых дистрибутивов Python в пределах одной системы, — это также приводит к неконтролируемому росту числа установленных пакетов. Для разрешения зависимостей conda использует приближённый SAT-solver, а задача SAT NP-полна, потому упорное использование только одного environment-а вскоре приведёт к тому, что вы будете часами ждать установки пакетов.

Выполнив в терминале код из ячейки ниже, вы создадите environment для нашего курса в директории ~:

conda create -n mipt-stats python=3.7 r=3.6 --yes

Эта команда создаст environment, в котором уже будут установлены Python и R, что сэкономит вам время в будущем.
Активируйте окружение, запустив в терминале ячейку ниже:

conda activate mipt-stats

Если вы захотите вернуться в базовое окружение, введите

Если вы хотите создать окружение в другой папке, то замените флаг -n на -o

conda create -o path/to/env python=3.7 r=3.6 --yes

Обратите внимание, что при этом вам придётся указывать полный путь при использовании команды conda activate:

conda activate /path/to/env

Установка mamba и основных пакетов¶

Выше упоминалось, что для разрешения зависимостей conda приближённо решает задачу SAT. К сожалению и стыду разработчиков из Continuum, SAT-solver в conda написан на pure Python, из-за чего он работает возмутительно медленно. Эту проблему решает mambaSAT-solver для conda, написанный на C++ компанией QuantStack.

conda install -c conda-forge mamba --yes

Далее везде используйте mamba install вместо conda install.

Аргумент -c позволяет указать репозиторий, в котором будет осуществляться поиск. Настоятельно рекомендуется использовать репозиторий conda-forge, т.к. там почти всегда можно найти актуальные версии пакетов, чего не скажешь об основном репозитории Anaconda. Причина в том, что conda-forge управляется сообществом пользователей conda, в то время как право добавлять пакеты в основной репозиторий имеют только разработчики из Continuum. Устанавливать пакеты из других репозиториев стоит только при необходимости, т.к. это может привести к переустановке уже установленных пакетов с их заменой на те версии из репозитория, из которого вы хотите что-то установить.

Теперь установим те пакеты, которые вам почти наверное понадобятся при выполнении домашних заданий.

Важное замечание: никогда не смешивайте pip и conda!

Подробное обсуждение этого вопроса можно прочитать на stackoverflow. Кратко, conda и pip были созданы для принципиально разных задач и «не знают» друг о друге: пакеты, которые вы установили через pip, будут видны изнутри conda, так как они ставятся напрямую в системный Python, но никакой инкапсуляции при этом не получится. Они не будут учитываться conda при разрешении зависимостей, а также могут быть параллельно установлены через conda в другой версии, что приведёт к странным ошибкам и неизбежному моральному падению.

Более того, даже если вы установите pip через conda, это всё ещё будет не то же самое, что установка пакетов через conda обычным образом. Гарантировать корректное разрешение зависимостей при этом будет нельзя.

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Быстрый ответ

Для установки пакетов в определённую среду Anaconda используйте следующие команды:

В момент активации среды pip автоматически установит пакеты в выбранное окружение.

Кинга Идем в IT: пошаговый план для смены профессии

Установка pip в среде conda

Перед тем как начать устанавливать пакеты, активируйте целевую среду conda, чтобы каждый проект был абсолютно изолирован и независим:

Теперь pip, отвечает за установку пакетов именно в эту среду:

Контроль за pip

Убедитесь, что вы используете pip именно из вашей среды

Проверьте, что вы используете версию pip именно из вашей среды, а не глобальную:

Пользователи Windows могут сделать это следующим образом:

Избегайте конфликта с переменной окружения PYTHONPATH:

Согласованность между pip и python

Убедитесь, что pip устанавливает пакеты для соответствующей версии Python:

Установка пакетов в Jupyter notebook

Когда вы работаете в Jupyter notebook, используйте следующий способ для установки пакетов:

Работа с пакетами, требующими особого внимания

Некоторые пакеты рекомендуется устанавливать с помощью pip:

Визуализация

Среду Anaconda можно рассматривать как эксклюзивную коллекцию пакетов Python:

Добавление нового пакета:

После установки новый пакет появляется в коллекции с остальными:

Учтите, что пакеты должны соответствовать требованиям вашей среды.

Проверьте, где был установлен пакет

Для проверки места установки пакета используйте:

Shell-скрипты и функции, специфичные для среды

Облегчите работу за счет использования shell-скриптов:

Теперь установка пакета упрощается до одной строки:

Официальная документация – ваш источник правильных инструкций

Для получения точных указаний обратитесь к официальной документации conda и pip.

Особенности работы на различных операционных системах

  • В Linux и macOS для устаревших версий используйте source activate myenv.
  • Пользователи Windows могут воспользоваться Anaconda Prompt для эффективного управления средами.

Решение проблем с зависимостями и конфликтами

  • Используйте pip check для обнаружения конфликтов между пакетами.
  • Для решения сложных зависимостей лучше использовать conda.
  • Для управления версиями пакетов, доступных только через pip, используйте файл требований.

Полезные материалы

  1. Обсуждение на Stack Overflow о различиях в применении pip и conda.
  2. Шпаргалка по использованию conda в командной строке.
  3. Официальное руководство по управлению различными окружениями с помощью conda.
  4. Блог Anaconda, где освещается использование conda и pip.
  5. Руководство по установке пакетов с помощью pip.
  6. Обучающий материал о виртуальных окружениях и пакетах в Python.
  7. Руководство пользователя pip с подробными инструкциями по установке и использованию.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • После переустановки windows нет доступа к папкам
  • Нет устройства ввода звука windows 10
  • Как узнать причину синего экрана windows 10 программа
  • Подключение сетевого принтера windows на linux
  • Как установить файл rpm в windows