Installing Python Packages with pip
In this step, you will learn how to install Python packages using pip. There are two main ways to install packages:
- Installing individual packages directly
- Installing multiple packages from a requirements file
Understanding Python Packages
Python packages are collections of modules that extend Python's functionality. Popular packages include:
- requests: For making HTTP requests
- numpy: For numerical computing
- pandas: For data analysis
- matplotlib: For data visualization
Installing Individual Packages
To install a single package, use the following command structure:
pip3 install package_name
Let's install the requests package, which is commonly used for making HTTP requests:
pip3 install requests
You should see output showing the download and installation progress, ending with a successful installation message.
Creating a Requirements File
Now, let's prepare a requirements file to specify multiple packages and their versions. Open the requirements.txt file created earlier:
nano ~/project/requirements.txt
Add the following lines to the file:
requests==2.25.1
numpy==1.20.1
Save the file by pressing Ctrl+O
, then Enter
, and exit by pressing Ctrl+X
.
This file specifies that we want to install:
- requests version 2.25.1
- numpy version 1.20.1
Specifying versions ensures consistency across different environments.
Installing from a Requirements File
Now, install the packages specified in the requirements file:
pip3 install -r ~/project/requirements.txt
You should see the packages being downloaded and installed. Note that if requests is already installed but with a different version, pip will update or downgrade it to match the version in requirements.txt.
Verifying Installed Packages
After installation, verify that the packages were installed correctly:
pip3 list
This command displays all installed Python packages. Look for requests
and numpy
in the list, which should show the exact versions specified in your requirements file:
Package Version
---------- -------
...
numpy 1.20.1
...
requests 2.25.1
...