Установка PIP для Python и базовые команды
Как любой серьёзный язык программирования, Python поддерживает сторонние библиотеки и фреймворки. Их устанавливают, чтобы не изобретать колесо в каждом новом проекте. Необходимы пакеты можно найти в центральном репозитории Python — PyPI (Python Package Index — каталог пакетов Python).
Однако скачивание, установка и работа с этими пакетами вручную утомительны и занимают много времени. Именно поэтому многие разработчики полагаются на специальный инструмент PIP для Python, который всё делает гораздо быстрее и проще.
Что такое PIP для Python?
Сама аббревиатура — рекурсивный акроним, который на русском звучит как “PIP установщик пакетов” или “Предпочитаемый установщик программ”. Это утилита командной строки, которая позволяет устанавливать, переустанавливать и деинсталлировать PyPI пакеты простой командой pip .
Если вы когда-нибудь работали с командной строкой Windows и с терминалом на Linux или Mac и чувствуете себя уверенно, можете пропустить инструкции по установке.
Устанавливается ли PIP вместе с Python?
Если вы пользуетесь Python 2.7.9 (и выше) или Python 3.4 (и выше), PIP устанавливается вместе с Python по умолчанию. Если же у вас более старая версия Python, то сначала ознакомьтесь с инструкцией по установке.
Правильно ли Python установлен?
Вы должны быть уверены, что Python должным образом установлен на вашей системе. На Windows откройте командную строку с помощью комбинации Win+X . На Mac запустите терминал с помощью Command+пробел , а на Linux – комбинацией Ctrl+Alt+T или как-то иначе именно для вашего дистрибутива.
Затем введите команду:
На Linux пользователям Python 3.x следует ввести:
Если вы получили номер версии (например, Python 2.7.5 ), значит Python готов к использованию.
Если вы получили сообщение Python is not defined (Python не установлен), значит, для начала вам следует установить Python. Это уже не по теме статьи. Подробные инструкции по установке Python читайте в теме: Скачать и установить Python.
Как установить PIP на Windows.
Следующие инструкции подойдут для Windows 7, Windows 8.1 и Windows 10.
- Скачайте установочный скрипт get-pip.py. Если у вас Python 3.2, версия get-pip.py должны быть такой же. В любом случае щелкайте правой кнопкой мыши на ссылке и нажмите “Сохранить как…” и сохраните скрипт в любую безопасную папку, например в “Загрузки”.
- Откройте командную строку и перейдите к каталогу с файлом get-pip.py.
- Запустите следующую команду: python get-pip.py
Как установить PIP на Mac
Современные версии Mac идут с установленными Python и PIP. Так или иначе версия Python устаревает, а это не лучший вариант для серьёзного разработчика. Так что рекомендуется установить актуальные версии Python и PIP.
Если вы хотите использовать родную систему Python, но у вас нет доступного PIP, его можно установить следующей командой через терминал:
Если вы предпочитаете более свежие версии Python, используйте Homebrew. Следующие инструкции предполагают, что Homebrew уже установлен и готов к работе.
Установка Python с помощью Homebrew производится посредством одной команды:
Будет установлена последняя версия Python, в которую может входить PIP. Если после успешной установки пакет недоступен, необходимо выполнить перелинковку Python следующей командой:
Как установить PIP на Linux
Если у вас дистрибутив Linux с уже установленным на нем Python, то скорее всего возможно установить PIP, используя системный пакетный менеджер. Это более удачный способ, потому что системные версии Python не слишком хорошо работают со скриптом get-pip.py, используемым в Windows и Mac.
Advanced Package Tool (Python 2.x)
Advanced Package Tool (Python 3.x)
pacman Package Manager (Python 2.x)
pacman Package Manager (Python 3.x)
Yum Package Manager (Python 2.x)
Yum Package Manager (Python 3.x)
Dandified Yum (Python 2.x)
Dandified Yum (Python 3.x)
Zypper Package Manager (Python 2.x)
Zypper Package Manager (Python 3.x)
Как установить PIP на Raspberry Pi
Как пользователь Raspberry, возможно, вы запускали Rapsbian до того, как появилась официальная и поддерживаемая версия системы. Можно установить другую систему, например, Ubuntu, но в этом случае вам придётся воспользоваться инструкциями по Linux.
Начиная с Rapsbian Jessie, PIP установлен по умолчанию. Это одна из серьёзных причин, чтобы обновиться до Rapsbian Jessie вместо использования Rapsbian Wheezy или Rapsbian Jessie Lite. Так или иначе, на старую версию, все равно можно установить PIP.
На Rapsbian для Python 2.x следует пользоваться командой pip, а для Python 3.x — командой pip3 при использовании команд для PIP.
Как обновить PIP для Python
Пока PIP не слишком часто обновляется самостоятельно, очень важно постоянно иметь свежую версию. Это может иметь значение при исправлении багов, совместимости и дыр в защите.
К счастью, обновление PIP проходит просто и быстро.
Для Mac, Linux, или Raspberry Pi:
На текущих версиях Linux и Rapsbian Pi следует использовать команду pip3.
Как устанавливать библиотеки Python с помощью PIP
Если PIP работоспособен, можно начинать устанавливать пакеты из PyPI:
Установка определённой версии вместо новейшей версии пакета:
Поиск конкретного пакета:
Просмотр деталей об установленном пакете:
Список всех установленных пакетов:
Список всех устаревших пакетов:
Обновление устаревших пакетов:
Следует отметить, что старая версия пакета автоматически удаляется при обновлении до новой версии.
How to install pip3 on my Mac?
I’m trying to install pip3, but I’m not having any luck. Also, I tried sudo install and it did not work. How could I install pip3 on my Mac?
11 Answers 11
UPDATED — Homebrew version after 1.5
On 1st March 2018 the python formula will be upgraded to Python 3.x and a python@2 formula will be added for installing Python 2.7 (although this will be keg-only so neither python nor python2 will be added to the PATH by default without a manual brew link —force). We will maintain python2, python3 and python@3 aliases.
So to install Python 3, run the following command:
Then, the pip or pip3 is installed automatically, and you can install any package by pip install
The older version of Homebrew
Not only brew install python3 but also brew postinstall python3
Note that you should check the console, as it might get you errors and in that case, the pip3 is NOT installed.
I solved the same problem with these commands:
For me brew postinstall python3 didn’t work. Found this solution on GitHub homebrew issues page:
Python3 was working successfully but without pip3. Tried many advises from stackoverflow, quora and others. (numerous installs and uninstalls)
Python3 was always fine but without pip3. Finally I downloaded Python3 from: https://www.python.org/downloads/
By simple mouse clicks and everything (Python3 + pip3) is working fine now.
To install or upgrade pip, download get-pip.py from the official site. Then run the following command:
and it will install pip for your python version which runs the script.
Similar to Oksana but add python3
Seem now work for pip3 under mac os x 10.13.3 Xcode 9.2
I ran the below where : matched the other : for other files in the /usr/local/lib/python3.7/site-packages/ directory:
I also encountered the same problem but brew install python3 does not work properly to install pip3 .
brre will throw the warning The post-install step did not complete successfully .
It has to do with homebrew does not have permission to /usr/local
Create the directory if not exist
Give the permissions inside /usr/local to homebrew so it can access them:
Now ostinstall python3
This will give you a successful installation
After upgrading to Mac OS Catalina, and upgrading all my vEnv modules, pip3 stopped working (gave error: «TypeError: ‘module’ object is not callable»).
Found question 58386953 which led to here and solution.
- Exit from vEnv (I started fresh shell)
- sudo python3 -m pip uninstall pip (this is necessary, but did not fix problem, because it removed the base Python pip, but didn’t touch my vEnv pip)
- sudo easy_install pip (reinstalling pip in base Python, not in vEnv)
- cd to your vEnv/bin and type «source activate» to get into vEnv
- rm pip pip3 pip3.6 (seems to be the only way to get rid of the bogus pip’s in vEnv)
- Now pip is gone from vEnv, and we can use the one in the base Python (I wasn’t able to successfully install pip into vEnv after deleting)
How do I install pip on macOS or OS X?
I spent most of the day yesterday searching for a clear answer for installing pip (package manager for Python). I can’t find a good solution.
How do I install it?
21 Answers 21
UPDATE (Jan 2019):
easy_install has been deprecated. Please use get-pip.py instead:
Old answer:
If you need admin privileges to run this, try:
⚡️ TL;DR — One line solution.
All you have to do is:
2019: ⚠️ easy_install has been deprecated. Check Method #2 below for preferred installation!
I made a gif, coz. why not?
Details:
⚡️ OK, I read the solutions given above, but here’s an EASY solution to install pip .
MacOS comes with Python installed. But to make sure that you have Python installed open the terminal and run the following command.
If this command returns a version number that means Python exists. Which also means that you already have access to easy_install considering you are using macOS/OSX .
ℹ️ Now, all you have to do is run the following command.
After that, pip will be installed and you’ll be able to use it for installing other packages.
Let me know if you have any problems installing pip this way.
✅ UPDATE (Jan 2019): METHOD #2: Two line solution —
easy_install has been deprecated. Please use get-pip.py instead.
First of all download the get-pip file
Now run this file to install pip
Another gif you said? Here ya go!
You can install it through Homebrew on OS X. Why would you install Python with Homebrew?
The version of Python that ships with OS X is great for learning but it’s not good for development. The version shipped with OS X may be out of date from the official current Python release, which is considered the stable production version. (source)
Homebrew is something of a package manager for OS X. Find more details on the Homebrew page. Once Homebrew is installed, run the following to install the latest Python, Pip & Setuptools:
I’m surprised no-one has mentioned this — since 2013, python itself is capable of installing pip , no external commands (and no internet connection) required.
This will create a similar install to what easy_install would.
Now, you could install external modules. For example
pip is available on OS X via easy_install .
Open a terminal and type:
When prompted for a password enter your normal login password.
After the installation has completed you should be able to use pip as expected.
note: this works for other python packages too
UPDATED 2020 August: MacOs Cataline
This python (v3) install pip3, in order to use only ‘pip’ , add an alias:
UPDATED 2019 October: MacOs Mojave
MacOS comes with python2 , but not with pip . Anyway, it’s better to manage it with homebrew, you must install it before:
WARNING: for a modern macOS (2019) this can install python3 , and for python2 you really need to do: brew install python@2
UPDATE: Python 3
If you install python3 , pip will be installed automatically.
NEW 2019: now to use pip version 3, use pip3 , or you can execute: python3 , to use version 3. When you install packages with pip3 they will be separated from python2 .
OLD: You need only to upgrade pip, but before that you need create a virtual environment to work with Python 3. You can use a project folder or any folder:
Check the versions:
To deactivate the environment:
Basically, this consists in:
- downloading get-pip.py. Be sure to do this by following a trusted link since you will have to run the script as root.
- call sudo python get-pip.py
The main advantage of that solution is that it install pip for the python version that has been used to run get-pip.py , which means that if you use the default OS X installation of python to run get-pip.py you will install pip for the python install from the system.
Most solutions that use a package manager (homebrew or macport) on OS X create a redundant installation of python in the environment of the package manager which can create inconsistencies in your system since, depending on what you are doing, you may call one installation of python instead of another.
Installing a separate copy of Python is a popular option, even though Python already comes with MacOS. You take on the responsibility to make sure you’re using the copy of Python you intend. But, the benefits are having the latest Python release and some protection from hosing your system if things go badly wrong.
To install Python using HomeBrew:
Now confirm that we’re working with our newly installed Python:
. should show a symbolic link to a path with «Cellar» in it like:
Pip should be installed along with Python. You might want to upgrade it by typing:
Now you’re ready to install any of the 50,000+ packages on PyPI.
Other Notes
Formerly, I’ve used get-pip.py to install pip. But, the docs warn that get-pip.py does not coordinate with package managers and may leave your system in an inconsistent state. Anyway, there’s no need, given that pip is now included with Python as of 2.7.9.
Note that pip isn’t the only package manager for Python. There’s also easy_install. It’s no good to mix the two, so don’t do it.
Finally, if you have both Python 2 and 3 installed, pip will point to whichever Python you installed last. Get in the habit of explicitly using either pip2 or pip3, so you’re sure which Python is getting the new library.