My first encounter with pip was trying to run a Python script that imported the requests library, only to be met with an import error. The fix turned out to be straightforward: using pip, Python's package installer.
To use pip, you need to have Python installed on your system. The basic command to install any library is:
pip install <package-name>
Best Practice: Using a Virtual Environment (venv)
Before installing packages everywhere, itβs best to create an isolated workspace for your project called a virtual environment. This keeps package dependencies for different projects separate so they don't clash with each other or your system's main Python installation.
1. Create the environment
Open your terminal in your project directory and run:
python -m venv venv
(This creates a folder named venv containing a standalone copy of Python and pip.)
2. Activate the environment
Before installing anything, activate it:
- Windows:
venv\Scripts\activate
- macOS / Linux:
source venv/bin/activate
Once activated, your terminal prompt will show (venv) at the beginning. Any pip install commands you run now will stay inside this isolated environment.
Bulk Installing Dependencies with requirements.txt
When you're running a Python script with multiple required packages, installing them one by one gets tedious. You can streamline this process by bulk installing everything at once using a requirements file.
Step 1: Create a requirements.txt file
Create a standard text file named requirements.txt in your project folder and list all your dependencies, one per line:
requests
pandas
numpy
Step 2: Run the bulk install command
With your virtual environment active, run:
pip install -r requirements.txt
Specifying Package Versions
Sometimes, the newest version of a library breaks compatibility with other packages in your project. To prevent this, you can specify exact version numbers directly inside your requirements.txt:
requests==2.31.0
pandas>=2.0.0
numpy<=1.24.0
-
==installs an exact version. -
>=or<=sets a minimum or maximum allowed version.
Top comments (0)