How to Create a Virtual Environment in Python?

What is a Virtual Environment?

A virtual environment is an isolated environment in Python where you can install packages without affecting the global Python installation or other projects. It ensures that dependencies for different projects do not conflict.

Steps to Create and Use a Virtual Environment

1. Ensure Python is Installed

Before creating a virtual environment, ensure Python is installed on your system. You can check this by running:

python --version

or

python3 --version

2. Install venv Module (If Not Already Installed)

The venv module is included by default in Python 3.3 and above. If you’re using an older version of Python, you may need to install the virtualenv package:

pip install virtualenv

3. Create a Virtual Environment

Navigate to the folder where you want your virtual environment to reside, then run the following command:

  • On Windows:
python -m venv myenv
  • On macOS/Linux:
python3 -m venv myenv

Here, myenv is the name of the virtual environment folder. You can replace it with any name you prefer.

4. Activate the Virtual Environment

Once created, activate the virtual environment:

  • On Windows (Command Prompt):
myenv\Scripts\activate
  • On Windows (PowerShell):
.\myenv\Scripts\Activate.ps1
  • On macOS/Linux:
source myenv/bin/activate

After activation, you’ll notice that the command prompt changes, showing the name of the virtual environment, e.g., (myenv).

5. Install Packages in the Virtual Environment

Now, any package you install using pip will be isolated to this environment:

pip install <package-name>

For example:

pip install numpy

6. Check Installed Packages

To inspect the installed packages in your virtual environment, execute:

pip list

7. Deactivate the Virtual Environment

Deactivate the virtual environment after you’re finished working.

deactivate

The prompt will return to its normal state.

8. Delete the Virtual Environment (Optional)

If you no longer need the virtual environment, you can delete the myenv folder:

  • On Windows:
rmdir /s myenv
  • On macOS/Linux:
rm -rf myenv

Advantages of Virtual Environments

  1. Project Isolation: Each project has its dependencies.
  2. Avoid version conflicts: Different projects might use different versions of the same library.
  3. Portability: Easily recreate environments on other systems using requirements.txt.

Using requirements.txt

To save and recreate dependencies:

  1. Save dependencies:
pip freeze > requirements.txt

2. Install dependencies from requirements.txt:

pip install -r requirements.txt