python virtualenv installation & usage guide

ยท

2 min read

You will have to use a virtual environment to manage different versions of packages. You are working on two projects, Project A uses Python version 3.5 and Project B uses Python version 3.8, in this case, you will need two virtual environments one of python3.5 and one of python3.8.

virtualenv is a CLI tool to manage Python virtual environments that needs a Python interpreter to run. It works by making an exact copy of your Python interpreter binary (the python or python3) in a local directory where it is installed.

How do I install virtualenv

Make sure you have Python and pip installed, if not you can follow this guide about installing python and pip.

  • On Ubuntu run

  • sudo apt-get update && sudo apt-get install virtualenv && pip install virtualenv

  • On Mac OS run:

  • easy_install virtualenv

  • On Windows run:

  • pip install virtualenv

How do I create a virtual environment in Python

You can create a virtual environment with different versions of Python. You can follow this guide to install a specific version of python.

Syntax of virtualenv create command

virtualenv -p <python_path> <name_of_environment>

python_path should be the path of your python executable and name_of_enviroment can be anything you like to name your environment.

To create, open your terminal and change the directory where you want to create a virtual environment.

  • For Python 3, run:

  • virtualenv -p python3 venv

  • For the specific versions of Python, run:

  • virtualenv -p <python3.x> venv

#Output

nitin@r777n:~/Workspace$ virtualenv -p python3 venv

created virtual environment CPython3.8.10.final.0-64 in 202ms

creator CPython3Posix(dest=/home/nitin/Workspace/venv, clear=False, global=False)

seeder FromAppData(download=False, pip=latest, setuptools=latest, wheel=latest, pkg_resources=latest, via=copy, app_data_dir=/home/nitin/.local/share/virtualenv/seed-app-data/v1.0.1.debian.1)

activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

How to activate/enable Python virtualenv

Open your terminal and change the directory where you have created your virtual environment.

  • On Ubuntu and Mac Os run:

  • source venv/bin/activate

  • On Windows, run:

  • venv\Scripts\activate

How to deactivate/disable Python virtualenv

To deactivate the Python virtual environment run:

deactivate

How to delete a virtual environment in Python

To completely delete or remove the virtual environment:

  • Open your terminal and change the directory where you have created a virtual environment.

  • Assuming your virtual environment folder is named venv

  • Run: rm -rf venv

I hope you learned about installing, creating, activating, deactivating, and deleting a virtual environment in this tutorial.

Did you find this article valuable?

Support Nitin Raturi by becoming a sponsor. Any amount is appreciated!

ย