Learn how to install and use external Python libraries with pip – a beginner-friendly guide with practical examples. Discover essential pip commands, popular libraries like requests, matplotlib, and beautifulsoup4, and best practices for dependency management.
pip
?pip
is the standard package manager for Python that allows you to install and manage additional libraries that aren’t part of the standard Python library.
pip
is InstalledBefore using pip
, check if it’s already installed (it usually comes with Python 3.4+):
pip --version
or
pip3 --version
pip
Commandspip install package_name
Example:
pip install requests
pip install package_name==version_number
Example:
pip install requests==2.25.1
pip install --upgrade package_name
Example:
pip install --upgrade requests
pip uninstall package_name
Example:
pip uninstall requests
pip list
pip show package_name
Example:
pip show requests
requests
import requests
# Make a GET request to a website
response = requests.get('https://www.example.com')
# Check if the request was successful
if response.status_code == 200:
print("Successfully fetched the page!")
print(f"Page content length: {len(response.text)} characters")
else:
print(f"Failed to fetch page. Status code: {response.status_code}")
python-dateutil
from dateutil import parser
from dateutil.relativedelta import relativedelta
# Parse a date string
date = parser.parse("June 5th 2023 10:30 PM")
print(f"Parsed date: {date}")
# Add 2 months to the date
new_date = date + relativedelta(months=+2)
print(f"Date after adding 2 months: {new_date}")
matplotlib
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# Create a simple line plot
plt.plot(x, y)
# Add labels and title
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Simple Line Plot')
# Display the plot
plt.show()
openpyxl
from openpyxl import Workbook
# Create a new Excel workbook
wb = Workbook()
# Get the active worksheet
ws = wb.active
# Add some data
ws['A1'] = "Name"
ws['B1'] = "Age"
ws['A2'] = "Alice"
ws['B2'] = 25
ws['A3'] = "Bob"
ws['B3'] = 30
# Save the workbook
wb.save("sample.xlsx")
print("Excel file created successfully!")
beautifulsoup4
import requests
from bs4 import BeautifulSoup
# Fetch a webpage
url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
response = requests.get(url)
# Parse the HTML content
soup = BeautifulSoup(response.text, 'html.parser')
# Extract and print the page title
title = soup.find('h1').text
print(f"Page title: {title}")
# Extract and print the first paragraph
first_paragraph = soup.find('p').text
print(f"\nFirst paragraph:\n{first_paragraph}")
For project-specific dependencies, it’s good practice to use virtual environments:
python -m venv myenv
myenv\Scripts\activate
source myenv/bin/activate
pip install package_name
deactivate
You can save all your project’s dependencies to a file:
pip freeze > requirements.txt
And later install them all at once:
pip install -r requirements.txt
Using external libraries with pip
greatly expands what you can do with Python. Start with simple libraries like requests
or matplotlib
, and gradually explore more specialized ones as you need them for your projects.