How to create a virtual environment in Python (Ubuntu)?

A Python virtual environment is a contained workspace facilitating students and researchers to build and execute Python projects with distinct libraries and dependencies, separate from their system-level Python setup. This setup permits the creation of isolated environments for various projects, preventing clashes between project-specific needs. Virtual environments promote effective and targeted coding practices, providing a structured and controlled environment conducive to educational projects.

Please choose Windows or Linux how-to guide:

Here’s how you can do it:

  1. Open Terminal:
    Open the Terminal by searching for it in the Ubuntu applications or pressing Ctrl + Alt + T.
  2. Navigate to the Desired Directory:
    Use the cd command to navigate to the directory to create your virtual environment. For example, to navigate to the /home/username/main_project directory, you would enter:
cd /home/username/main_project
  1. Install venv if required:
    Check if the venv module is already installed by entering:
python -m venv --help

If it’s not installed, you can install it using the following command:

sudo apt install python-venv
  1. Create the Virtual Environment:
    Once you’re in the desired directory and have venv installed, use the following command to create a virtual environment named “collegelib_env” (you can replace “collegelib_env” with your preferred name):
python -m venv collegelib_env

This will create a directory named “collegelib_env” in your current directory, containing the virtual environment.

  1. Activate the Virtual Environment:
    To activate the virtual environment, use the following command:
source collegelib_env/bin/activate

You’ll notice the prompt changes, indicating you’re now in the virtual environment.

  1. Install Packages:
    While the virtual environment is active, you can use the pip command to install packages, and they will be installed only in the virtual environment, keeping them separate from your system-wide Python installation. For example:
pip install package_name
  1. Deactivate the Virtual Environment:
    When you’re done working within the virtual environment, you can deactivate it by running the deactivate command:

Once deactivated, you’ll return to the system-wide Python environment.

Remember that you’ll need to activate the virtual environment whenever you want to work within it and deactivate it when you’re done. This helps to keep your project’s dependencies isolated from other projects and your system-wide Python environment.

Please note that the actual paths and commands might vary slightly based on your Ubuntu version and Python installation, but the general approach remains the same.