Create a virtual environment in python

What if you want to run two Python programs with different versions of a library on a single computer? Then we need to use virtual environments.

·

2 min read

Create a virtual environment in python

Suppose there is below script

➜  cat python2.py
print "anwer is :", 2+2

Installing Virtual Env:

pip install virtualenv --upgrade

Check version:

virtualenv --version
16.7.9

Create environment:

virtualenv python2_env
#Output of above command
python executable in /Users/siddartha/Desktop/delete/hashnodevm/python2_env/bin/python
Installing setuptools, pip, wheel...
done.

This creates below directories

-python2_env
   ----bin
   ----include
   ----lib

use python2_env to use python2 as default

which python2
/usr/bin/python2

#this creates python2 as default interpreter 
virtualenv -p /usr/bin/python2 python2_env

now the folder contains below

-python2_env
   ----bin
          ---- python2 --> python 
   ----include
   ----lib

Activating Virtual Environments We will have (base) as our environment. In order to activate python2_env, use below:

source python2_env/bin/activate

So python environment gets modified to use python2

List packages:

(python2_env) ➜   pip list

Package    Version
---------- -------
pip        20.3.4
setuptools 44.1.1
wheel      0.36.2

How to exit?

deactivate

We now switch back to base environment

Configuring virtual environments

Create a shell script as below

cat run_python2_script.sh

source python2_env/bin/activate
python python2.py
deactivate

To execute shell script

chmod +x run_python2_script.sh
./run_python2_script.sh

SUMMARY

#installing virtual environment
pip install virtualenv --upgrade

#Creating virtual environment
virtualenv python2_env

#Activating
source python2_env/bin/activate

#To check the library versions
pip list

#Deactivating
deactivate

How to create new virtual environments. Another method in latest python python -m venv venvName

This will create a new virtual environment called venvName in the current folder.

Additional information:

Found below link which is useful: blog.teclado.com/python-virtual-environment..