Python Virtual Environment

Learn to create python virtual environment in Linux

Featured image

Creating Virtual Environement using PIP

Youtube Video

PIP Setup

For creating virtual environment you will require pip

Check if pip is installed:

$ pip --version
$ pip3 --version

If it is not installed then you can install using:

$ sudo apt install python3-pip

Install Virtualenv

$ pip3 install virtualenv
$ pip3 install virtualenvwrapper

Check virtualenv:

$ which virtualenv

Make sure you note the output as this will be added later in .bashrc file

Setup bashrc file

This is done so that you can use shortcut commands to create, access and delete veritual environments.

$ nano ~/.bashrc

At the end of the .bashrc file add:

#Virtualenvwraaper settings
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_VIRTUALENV=/home/harsh/.local/bin/virtualenv
source ~/.local/bin/virtualenvwrapper.sh

To save press CTRL+O to Exit press CTRL+X

Activate it on current terminal:

$ source ~/.bashrc

Create new Virtualenv

$ mkvirtualenv <name>                       # Demo
$ mkvirtualenv test_env                     # Create New Virtual Env
$ mkvirtualenv myvenv --python=python3.7    # Create New Virtual Env with python version

Activate Virtual Environment

$ workon <name>
$ workon test_env

This will give something like:

(test_env) harsh@harsh-VM:~$

Deactivate Virtual Environment

$ deactivate

This will give something like:

harsh@harsh-VM:~$

Copy Virtual Environment

$ cpvirtualenv <old> <new>
$ cpvirtualenv test_env test_env1

Delete Virtual Environement

$ rmvirtualenv <name>
$ rmvirtualenv test_env

Creating Virtual Environement using Conda (Anaconda)

Setup conda

Check if conda is present

$ conda -V

# Update Conda
$ conda update conda

If conda not installed then checkout: Anaconda

Create Virtual Environement

$ conda create -n [Virtual Environment Name] python=[Version you want to install] anaconda

$ conda create -n test_env python=3.8 anaconda

Activate Virtual Environement

$ conda activate test_env

Deactivate Virtual Environement

$ conda deactivate