Skip to content

How to Resolve "NameError: name 'pip' is not defined" in Python

Fix the Python error when trying to use pip install inside a script by learning the correct ways to install packages from the command line or programmatically.

The NameError: name 'pip' is not defined error in Python occurs when you try to use the pip command inside a Python script or interactive Python session as if it were a Python function or variable. pip is a command-line tool, not a Python object.

This guide explains the cause of this error and provides the correct ways to install packages: from the command line and programmatically (if absolutely necessary).

Understanding the Error: pip is a Command-Line Tool

pip is the package installer for Python. It's a command-line tool that you use in your terminal (or command prompt), not within a Python script or interactive session.

Incorrect (within a Python script or interactive session):

>>> pip install requests
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pip' is not defined

You can not directly call pip install ... inside a Python script like this. This is the fundamental cause of the NameError.

Installing Packages from the Command Line (The Correct Way)

The correct way to install a Python package is to use pip from your terminal (or command prompt):

  • Open your terminal/command prompt:

    • Windows: Search for "cmd" (Command Prompt) or "PowerShell" and open it.
    • macOS: Open "Terminal" (Applications/Utilities/Terminal.app).
    • Linux: Open your terminal application (usually Ctrl+Alt+T).
  • Run pip install:

    pip install requests  # Installs the 'requests' package
    • pip3: If you have both Python 2 and Python 3 installed, you might need to use pip3 to install packages for Python 3:

      pip3 install requests
    • python -m pip: If you're having trouble with pip or pip3 being found, use this more explicit form:

      python -m pip install requests  # Use with your default Python version
      python3 -m pip install requests # Use with Python 3 (if that's your default)
      py -m pip install requests       # Use with the py alias on Windows

      This ensures you're using the pip associated with the correct Python interpreter.

    • Permissions Errors: If you get a permissions error (especially on Linux/macOS), you have a few options:

      • sudo (use with caution): sudo pip3 install requests. Be very careful when using sudo with pip. It's generally better to use a virtual environment (see below) or the --user option.
      • --user: Install the package for your user account only: pip install requests --user. This doesn't require administrator privileges.
      • Virtual Environments (Best Practice): The best solution is to use a virtual environment, which avoids all permission problems and keeps your project dependencies isolated. See the next section.
  • Virtual Environments (Strongly Recommended): Before installing any packages, create and activate a virtual environment:

python3 -m venv venv  # Create a virtual environment named 'venv'
python -m venv venv
py -m venv venv

source venv/bin/activate    # Linux/macOS
venv\Scripts\activate.bat   # Windows (cmd.exe)
venv\Scripts\Activate.ps1   # Windows (PowerShell)

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

pip install requests

Installing Packages from Within a Python Script (Use with Caution)

While not generally recommended, you can install packages from within a Python script using the subprocess module. This is useful in specific situations, like setup scripts or when you absolutely need to ensure a dependency is installed before continuing.

import sys
import subprocess

def install_package(package_name):
    """Installs a package using pip.  Use with caution!"""
    try:
        subprocess.check_call([sys.executable, '-m', 'pip', 'install', package_name],
                            stdout=subprocess.DEVNULL # Optionally hide output
                            )
        print(f"Successfully installed {package_name}")
    except subprocess.CalledProcessError as e:
        print(f"Error installing {package_name}: {e}")
        sys.exit(1)  # Exit if installation fails


install_package('requests') # Install requests module.

import requests
  • sys.executable: This is the absolute path to the Python interpreter that's currently running. This ensures you're using the correct pip.
  • subprocess.check_call(...): This runs a command (in this case, pip install) as a subprocess. Using check_call ensures that an exception is raised if the command fails (e.g., if the package doesn't exist).
  • stdout=subprocess.DEVNULL: This hides the output of the pip install command. Remove this if you want to see the installation output.
  • Security: While this is safer than using os.system(), you still need to be very careful about where package_name comes from. If it's based on user input, validate it thoroughly to prevent command injection vulnerabilities.
  • List Pass the command as a list, to avoid using shell.

Upgrading pip

It's a good idea to keep pip itself up-to-date:

python -m pip install --upgrade pip   # Or python3 -m pip ...

Conclusion

The NameError: name 'pip' is not defined error arises because pip is a command-line tool, not a Python object.

  • You must run pip commands from your terminal, not directly within Python code.
  • The best practice is to manage dependencies using a requirements.txt file and virtual environments.
  • If you absolutely need to install a package from within a script, use subprocess.check_call() with careful input validation, but this is generally discouraged.
Navigation