- Python. Урок 16. Установка пакетов в Python
- Где взять отсутствующий пакет?
- Менеджер пакетов в Python – pip
- Установка pip
- Обновление pip
- Использование pip
- Установка пакета
- Удаление пакета
- Обновление пакетов
- Просмотр установленных пакетов
- Поиск пакета в репозитории
- Где ещё можно прочитать про работу с pip?
- P.S.
- Step 5: Install packages in your Python environment
- View environments
- Install packages using the Python Environments window
- Run the program
- Installing PackagesВ¶
- Requirements for Installing PackagesВ¶
- Ensure you can run Python from the command lineВ¶
- Ensure you can run pip from the command lineВ¶
- Ensure pip, setuptools, and wheel are up to dateВ¶
- Optionally, create a virtual environmentВ¶
- Creating Virtual EnvironmentsВ¶
Python. Урок 16. Установка пакетов в Python
В процессе разработки программного обеспечения на Python часто возникает необходимость воспользоваться пакетом, который в данный момент отсутствует на вашем компьютере. О том, откуда взять нужный вам пакет и как его установить, вы узнаете из этого урока.
Где взять отсутствующий пакет?
Необходимость в установке дополнительного пакета возникнет очень быстро, если вы решите поработать над задачей, за рамками базового функционала, который предоставляет Python . Например: работа с web , обработка изображений, криптография и т.п. В этом случае, необходимо узнать, какой пакет содержит функционал, который вам необходим, найти его, скачать, разместить в нужном каталоге и начать использовать. Все эти действия можно сделать вручную, но этот процесс поддается автоматизации. К тому же скачивать пакеты с неизвестных сайтов может быть довольно опасно.
К счастью для нас, в рамках Python, все эти задачи решены. Существует так называемый Python Package Index (PyPI) – это репозиторий, открытый для всех Python разработчиков, в нем вы можете найти пакеты для решения практически любых задач. Там также есть возможность выкладывать свои пакеты. Для скачивания и установки используется специальная утилита, которая называется pip .
Менеджер пакетов в Python – pip
Pip – это консольная утилита (без графического интерфейса). После того, как вы ее скачаете и установите, она пропишется в PATH и будет доступна для использования.
Эту утилиту можно запускать как самостоятельно:
так и через интерпретатор Python :
Ключ -m означает, что мы хотим запустить модуль (в данном случае pip ). Более подробно о том, как использовать pip , вы сможете прочитать ниже.
Установка pip
При развертывании современной версии Python (начиная с P ython 2.7.9 и Python 3.4),
pip устанавливается автоматически. Но если, по какой-то причине, pip не установлен на вашем ПК, то сделать это можно вручную. Существует несколько способов.
Будем считать, что Python у вас уже установлен, теперь необходимо установить pip . Для того, чтобы это сделать, скачайте скрипт get-pip.py
и выполните его.
При этом, вместе с pip будут установлены setuptools и wheels . Setuptools – это набор инструментов для построения пакетов Python . Wheels – это формат дистрибутива для пакета Python . Обсуждение этих составляющих выходит за рамки урока, поэтому мы не будем на них останавливаться.
Способ для Linux
Если вы используете Linux , то для установки pip можно воспользоваться имеющимся в вашем дистрибутиве пакетным менеджером. Ниже будут перечислены команды для ряда Linux систем, запускающие установку pip (будем рассматривать только Python 3, т.к. Python 2 уже морально устарел, а его поддержка и развитие будут прекращены после 2020 года).
Обновление pip
Если вы работаете с Linux , то для обновления pip запустите следующую команду.
Для Windows команда будет следующей:
Использование pip
Далее рассмотрим основные варианты использования pip : установка пакетов, удаление и обновление пакетов.
Установка пакета
Pip позволяет установить самую последнюю версию пакета, конкретную версию или воспользоваться логическим выражением, через которое можно определить, что вам, например, нужна версия не ниже указанной. Также есть поддержка установки пакетов из репозитория. Рассмотрим, как использовать эти варианты.
Установка последней версии пакета
Установка определенной версии
Установка пакета с версией не ниже 3.1
Установка Python пакета из git репозитория
Установка из альтернативного индекса
Установка пакета из локальной директории
Удаление пакета
Для того, чтобы удалить пакет воспользуйтесь командой
Обновление пакетов
Для обновления пакета используйте ключ –upgrade.
Просмотр установленных пакетов
Для вывода списка всех установленных пакетов применяется команда pip list .
Если вы хотите получить более подробную информацию о конкретном пакете, то используйте аргумент show .
Поиск пакета в репозитории
Если вы не знаете точное название пакета, или хотите посмотреть на пакеты, содержащие конкретное слово, то вы можете это сделать, используя аргумент search .
Где ещё можно прочитать про работу с pip?
В сети довольно много информации по работе с данной утилитой.
Python Packaging User Guide – набор различных руководств по работе с пакетами в Python
P.S.
Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
Step 5: Install packages in your Python environment
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 those 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 additional information about working with environments, see How to create and manage Python environments in Visual Studio environments.
You can also open the Python Environments window by selecting the Solution Explorer window and using the Ctrl+K, Ctrl+` keyboard shortcut. If the shortcut doesn’t work and you can’t find the Python Environments window in the menu, it’s possible you haven’t installed the Python workload. See How to install Python support in Visual Studio for guidance about how to install Python.
The environment’s Overview tab provides quick access to an Interactive window for that environment along with the environment’s installation folder and interpreters. For example, select Open interactive window and an Interactive window for that specific environment appears in Visual Studio.
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. Alternatively, you can use the project you previously created and replace the code.
With a Python project open, you can also open the Python Environments window from Solution Explorer by right-clicking Python Environments and selecting View All Python Environments
Looking at the editor window, you’ll notice that if you hover over the numpy and matplotlib import statements that they are not resolved. That’s because the packages have not been installed to the default global 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 will 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. This will install matplotlib , as well as any packages it depends on (in this case that includes numpy ).
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.
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:
Installing PackagesВ¶
This section covers the basics of how to install Python packages .
It’s important to note that the term “package” in this context is being used to describe a bundle of software to be installed (i.e. as a synonym for a distribution ). It does not to refer to the kind of package that you import in your Python source code (i.e. a container of modules). It is common in the Python community to refer to a distribution using the term “package”. Using the term “distribution” is often not preferred, because it can easily be confused with a Linux distribution, or another larger software distribution like Python itself.
Requirements for Installing PackagesВ¶
This section describes the steps to follow before installing other Python packages.
Ensure you can run Python from the command lineВ¶
Before you go any further, make sure you have Python and that the expected version is available from your command line. You can check this by running:
You should get some output like Python 3.6.3 . If you do not have Python, please install the latest 3.x version from python.org or refer to the Installing Python section of the Hitchhiker’s Guide to Python.
If you’re a newcomer and you get an error like this:
It’s because this command and other suggested commands in this tutorial are intended to be run in a shell (also called a terminal or console). See the Python for Beginners getting started tutorial for an introduction to using your operating system’s shell and interacting with Python.
If you’re using an enhanced shell like IPython or the Jupyter notebook, you can run system commands like those in this tutorial by prefacing them with a ! character:
It’s recommended to write
Due to the way most Linux distributions are handling the Python 3 migration, Linux users using the system Python without creating a virtual environment first should replace the python command in this tutorial with python3 and the python -m pip command with python3 -m pip —user . Do not run any of the commands in this tutorial with sudo : if you get a permissions error, come back to the section on creating virtual environments, set one up, and then continue with the tutorial as written.
Ensure you can run pip from the command lineВ¶
Additionally, you’ll need to make sure you have pip available. You can check this by running:
If you installed Python from source, with an installer from python.org, or via Homebrew you should already have pip. If you’re on Linux and installed using your OS package manager, you may have to install pip separately, see Installing pip/setuptools/wheel with Linux Package Managers .
If pip isn’t already installed, then first try to bootstrap it from the standard library:
If that still doesn’t allow you to run python -m pip :
Run python get-pip.py . 2 This will install or upgrade pip. Additionally, it will install setuptools and wheel if they’re not installed already.
Be cautious if you’re using a Python install that’s managed by your operating system or another package manager. get-pip.py does not coordinate with those tools, and may leave your system in an inconsistent state. You can use python get-pip.py —prefix=/usr/local/ to install in /usr/local which is designed for locally-installed software.
Ensure pip, setuptools, and wheel are up to dateВ¶
While pip alone is sufficient to install from pre-built binary archives, up to date copies of the setuptools and wheel projects are useful to ensure you can also install from source archives:
Optionally, create a virtual environmentВ¶
See section below for details, but here’s the basic venv 3 command to use on a typical Linux system:
This will create a new virtual environment in the tutorial_env subdirectory, and configure the current shell to use it as the default python environment.
Creating Virtual EnvironmentsВ¶
Python “Virtual Environments” allow Python packages to be installed in an isolated location for a particular application, rather than being installed globally. If you are looking to safely install global command line tools, see Installing stand alone command line tools .
Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python3.6/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.
Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.
In all these cases, virtual environments can help you. They have their own installation directories and they don’t share libraries with other virtual environments.
Currently, there are two common tools for creating Python virtual environments:
venv is available by default in Python 3.3 and later, and installs pip and setuptools into created virtual environments in Python 3.4 and later.
virtualenv needs to be installed separately, but supports Python 2.7+ and Python 3.3+, and pip , setuptools and wheel are always installed into created virtual environments by default (regardless of Python version).