zaro

How to install Python packages in VS Code?

Published in Python Development 3 mins read

Installing Python packages in VS Code is straightforward, typically involving using the terminal within VS Code with the pip package installer. Here's a breakdown of the process:

  1. Open the Integrated Terminal: In VS Code, go to View > Terminal (or use the shortcut Ctrl + on Windows/Linux or Cmd + on macOS). This opens a terminal window within VS Code.

  2. Verify Python and pip are installed: In the terminal, type python --version and pip --version. If Python or pip are not installed, you'll need to install them first. Refer to the official Python documentation for installation instructions for your operating system. Make sure pip is updated: python -m pip install --upgrade pip

  3. Install the desired package: Use the pip install command followed by the name of the package you want to install. For example, to install the requests package, type pip install requests and press Enter.

  4. Specify a Python interpreter (if needed): If you have multiple Python interpreters installed and want to install the package for a specific interpreter, you can use the full path to that interpreter's pip. First, identify the path to the interpreter, then use that path to call pip. For example:

    • Windows: C:\Python39\python.exe -m pip install requests
    • macOS/Linux: /usr/bin/python3 -m pip install requests or /opt/homebrew/bin/python3 -m pip install requests (example for Homebrew installation on Apple Silicon)
  5. Using a Virtual Environment (Recommended): For project-specific dependencies, use a virtual environment:

    • Create a virtual environment: python -m venv .venv (this creates a .venv directory in your project folder)
    • Activate the virtual environment:
      • Windows: .venv\Scripts\activate
      • macOS/Linux: source .venv/bin/activate
    • Install packages: pip install <package_name>
  6. Verify the installation: After the installation is complete, you can verify that the package has been installed by importing it in a Python script or in the interactive Python interpreter. Open a new Python file (e.g., test.py) and add the line import requests. If no errors occur, the package is installed correctly. You can also list all installed packages using pip list.

Example Scenario:

Let's say you want to install the numpy package.

  1. Open the VS Code terminal (Ctrl + `).
  2. Type pip install numpy and press Enter.
  3. Wait for the installation to complete.
  4. Open a Python file and type import numpy. Run the file. If it runs without errors, numpy is successfully installed.

By following these steps, you can easily install Python packages within VS Code, ensuring your project has the necessary dependencies. Using virtual environments is highly recommended for managing dependencies on a per-project basis.