Python Virtualenv

Python Virtualenv

Python Virtualenv

We have dependencies issue while installing different version of python module.
In this case virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

Let me show you how

Virtualenv installation

    1) Using Python 2x
        Syntax: pip install virtualenv

    2) Uisng Python 3x
        Syntax: pip3 install virtualenv

root@juniour:~# pip install virtualenv
Collecting virtualenv
Downloading https://files.pythonhosted.org/packages/b6/30/96a02b2287098b23b875bc8c2f58071c35d2efe84f747b64d523721dc2b5/virtualenv-16.0.0-py2.py3-none-any.whl (1.9MB)
100% |████████████████████████████████| 1.9MB 628kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv

To confirm installation run:
root@juniour:~# virtualenv --version
16.0.0

Creating environment using virtualenv
We will create the directory named pyenv, and will use this directory as environment.

Creating python 3x environment
Syntax: virtualenv -p python3
root@juniour:~# virtualenv -p python3 pyenv
Running virtualenv with interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /root/pyenv/bin/python3
Also creating executable in /root/pyenv/bin/python
Installing setuptools, pip, wheel...done.
root@juniour:~# cd pyenv

We will check for python path
root@juniour:~/pyenv# which python
/usr/bin/python

Activate the environment
Syntax: source bin/active
root@juniour:~/pyenv# source bin/activate
(pyenv) root@juniour:~/pyenv# which python
/root/pyenv/bin/python

You can see that now python points to pyenv environment python (/root/pyenv/bin/python)

Your environment is active under pyenv directory.
Lets install a package (psutil)

(pyenv) root@juniour:~/pyenv# pip install psutil
Collecting psutil
Downloading https://files.pythonhosted.org/packages/7d/9a/1e93d41708f8ed2b564395edfa3389f0fd6d567597401c2e5e2775118d8b/psutil-5.4.7.tar.gz (420kB)
100% |████████████████████████████████| 430kB 1.6MB/s
Building wheels for collected packages: psutil
Running setup.py bdist_wheel for psutil ... done
Stored in directory: /root/.cache/pip/wheels/e2/9d/ea/1913d16f19bb927c32197308dec69cd8d10b61be8f7e265524
Successfully built psutil
Installing collected packages: psutil
Successfully installed psutil-5.4.7

Whatever changes you will do here will will not effect default python of the system.

When done with test, you exit the environment using deactive command
(pyenv) root@juniour:~/pyenv# deactivate
root@juniour:~/pyenv#

Uninstalling environment: delete the environment directory.

root@juniour:~# rm -rf pyenv
root@juniour:~#

Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *