Explain Codes LogoExplain Codes Logo

Importerror: No module named requests

python
importerror
pip-installation
virtual-environments
Anton ShumikhinbyAnton Shumikhin·Dec 24, 2024
TLDR

To quickly eradicate the ImportError concerning the requests module, install it via:

pip install requests

Should you be using Python 3 or higher, use pip3 in place of pip. Confirm that the virtual environment is activated before installing. This satisfies the import requests in your script.

Verifying environment

Ensure your pip aligns with your Python version. You can check your Python version with:

python --version # Returns Python version

And for pip:

pip --version # Who's pip and what's he doing?

On Windows systems, remember, it could be py rather than python or python3.

Installed packages

You might have installed requests but it could be in a different Python environment. Use the following command to list your installed packages:

pip list # Show me what you got!

If requests is present in this list, your script might be running in an unexpected environment.

Forced march: Manual installation

Automatic installations can sometimes be cranky. Here, manual installation comes to the rescue. Download the source of requests from PyPI, extract the archive. Navigate to the directory via terminal or cmd window and conjure the following:

python setup.py install # Manual labor :(

Confirm that the PATHs of Python and pip are correctly etched into your environment variables. This varies across operation systems but generally involves a journey of adding the Python and pip directory paths to the system PATH.

OS specifics: Linux & macOS

Linux users, bring forth the might of your package manager, like:

sudo apt-get install python-requests # For Python 2.x sudo apt-get install python3-requests # For Python 3.x, who's on Python 2 anyway?

macOS users armed with Homebrew should invoke:

brew install python # Pour me some Python, will ya? brew install python3

Then you can enjoy pip or pip3 as shown before.

Fancy bubbles: Virtual environments

Virtual environments save you from the chaos caused by system-wide installations. They let you wrap up dependencies for individual projects without causing a ruckus in global installs. Create one with:

python3 -m venv myenv # Give me my own bubble 🧪

And welcome yourself into this paradise:

source myenv/bin/activate # Fancy Unix-like systems myenv\Scripts\activate # Windows lovers

In this isolated bubble, install requests and enjoy a tranquil coding experience.