Introduction
Pip is a package manager for Python, it downloads, installs, uninstalls, and updates python packages using the Python Package Index.
Pip is capable of downloading libraries from a wide range of open-source projects, meaning you can download and import multiple packages without having to install each one manually.
How to install Pip using apt
# python 2
apt install python-pip
# python 3
apt install python3-pip
If your user doesn't have root privileges, you'll need to use sudo
to install Pip:
# python 2
sudo apt install python-pip
# python 3
sudo apt install python3-pip
Installing Pip packages
Installing packages using Pip is like installing packages using apt
.
Replace the apt
keyword with pip
or pip3
, depending on the version you're using.
# python 2
pip install requests
# python 3
pip3 install requests
Uninstalling Pip packages
Use the uninstall
keyword to remove packages:
# python 2
pip uninstall requests
# python 3
pip3 uninstall requests
Importing Pip packages
In the previous examples, we downloaded the requests
library.
To use the requests
package in your script import
it:
import requests
The following demo prints the responseText
(HTML) from https://example.com:
url = "https://example.com"
headers = { "Accept-Encoding": "identity" }
response = requests.get(url, headers = headers)
print(response.text)
Updating Pip using apt
and Pip
The --upgrade
flag is available on both the pip
and apt
commands.
This means that you can pass the --upgrade
flag to the install
command of both package managers:
# python 2
pip install --upgrade pip
sudo apt install --upgrade python-pip
# python 3
pip3 install --upgrade pip
sudo apt install --upgrade python3-pip
Fixing directory errors
Pip will try it's best to install packages in the proper directories, this might not work as expected if you're using sudo
to install packages.
To prevent getting errors such as: parent directory not owned by the current user
, provide the -H
flag to the sudo
command:
# python 2
sudo -H pip install --upgrade pip
# python 3
sudo -H pip3 install --upgrade pip
This sets the $HOME
environment variable to the home directory of the target user. In this case, root (sudo).
In other words, you're installing the package as root, but in the Pip directory of the user you logged in as.