Python Virtualenv Tutorial

28/12/2020
The headaches of dependency management are common to developers. One errant update requires hours of research to correct.  Often multiple applications overlap on library dependency requirements.  This could cause two applications running in the same environment to require two version of the same library.  These type of conflicts could cause a number of issues both in development and production.Enter Virtualenv.  Virtualenv is a tool that creates dependency silos.  It allows you to deploy applications to a single environment with isolated dependencies. Docker employs a similar strategy at the OS level. Virtualenv segregates only at the Python and library level — that is, the environments Python executable and libraries are unique to that virtual environment.  So instead of using the libraries installed at the OS environment level, you can separate Python versions and libraries into siloed virtual environments.  This allows you to deploy multiple applications in the same OS environment with different versions of the same dependencies.

Install Virtualenv

The install of Virtualenv is straight forward. Using pip, you can execute the below command from the terminal.

$ pip install virtualenv

Alternatively, if using Anaconda you will need to use the below terminal command instead.

$ conda install virtualenv

Your terminal output should look similar to the below.

Bradleys-Mini:~ BradleyPatton$ pip install virtualenv
Collecting virtualenv
Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
100% |████████████████████████████████| 1.8MB 267kB/s
Installing collected packages: virtualenv
Successfully installed virtualenv-15.1.0
Bradleys-Mini:~ BradleyPatton$

Create an Environment

Virtualenv has one main command. The below line executed from the terminal will create a new “silo” or virtual Python environment in the Tutorial directory.

$ virtualenv Tutorial

You should get some terminal output like below after executing.

Bradleys-Mini:site-packages BradleyPatton$ virtualenv Tutorial
Overwriting /Users/BradleyPatton/anaconda/lib/python2.7/site-
packages/Tutorial/lib/python2.7/orig-prefix.txt with new content
New python executable in /Users/BradleyPatton/anaconda/lib/python2.7/site-
packages/Tutorial/bin/python
copying /Users/BradleyPatton/anaconda/bin/python =>
/Users/BradleyPatton/anaconda/lib/python2.7/site-packages/Tutorial/bin/python
copying /Users/BradleyPatton/anaconda/bin/../lib/libpython2.7.dylib =>
/Users/BradleyPatton/anaconda/lib/python2.7/site-packages/Tutorial/lib/
libpython2.7.dylib
Installing setuptools, pip, wheel…done.

The virtualenv command will build a directory structure including a binary, library and include directory for the new virtual environment that was created.

Bradleys-Mini:Tutorial BradleyPatton$ ls
bin                            lib
include                        pip-selfcheck.json
Bradleys-Mini:Tutorial BradleyPatton$

/bin contains your executables most notably Python and pip.

Bradleys-Mini:bin BradleyPatton$ ls
activate                    easy_install-2.7           python-config
activate.csh                pip                        python2
activate.fish               pip2                        python2.7
activate_this.py           pip2.7                       wheel
easy_install                 python
Bradleys-Mini:bin BradleyPatton$

The /lib and /include directories include supporting files for Python and the application to be developed.

Activate Virtualenv

The activation script updates your path so that you can utilize this virtual environment without the hassle of navigating to the directory. It makes it a bit easier to use, but could be skipped if you are a terminal ninja and don’t mind the key strokes.

In the /bin directory there is an activate BASH script. You can execute using the below.

$ ./activate

If you will note from my fumbling below that I had to modify the permission of the file to execute. I used the CHMOD 700 activate command to update the permissions. You may also need to make this update prior to running the activate script.

Bradleys-Mini:bin BradleyPatton$ ls
activate              easy_install-2.7     python-config
activate.csh           pip                  python2
activate.fish          pip2                 python2.7
activate_this.py       pip2.7                wheel
easy_install           python
Bradleys-Mini:bin BradleyPatton$ ./activate
-bash: ./activate: Permission denied
Bradleys-Mini:bin BradleyPatton$ sudo ./activate
Password:
sudo: ./activate: command not found
Bradleys-Mini:bin BradleyPatton$ chmod 700 activate
Bradleys-Mini:bin BradleyPatton$ ./activate
Bradleys-Mini:bin BradleyPatton$

Deactivate Virtualenv

To undo the environment variable changes that were made by activate run the following command from the terminal. This will revert your path changes like they never happened. It’s as simple as that.

$ deactivate

Removing an Environment

Removing a virtual environment is as simple as rm. Simply type the following to remove the directory and recursively its contents.

$ rm -r TutorialtoRemove

Now What

Well, now you need to install your libraries and application in the new virtual environment.  Pip makes sourcing your libraries easy.

I won’t go into the subtleties of pip some of which can be found here, but I will demonstrate a single pip install.

$ pip install pandas

 

(Tutorial) Bradleys-Mini:bin BradleyPatton$ pip install pandas
Collecting pandas
Using cached pandas-0.22.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9
_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl
Collecting numpy>=1.9.0 (from pandas)
Using cached numpy-1.14.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9
_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl
Collecting python-dateutil (from pandas)
Using cached python_dateutil-2.6.1-py2.py3-none-any.whl
Collecting pytz>=2011k (from pandas)
Using cached pytz-2017.3-py2.py3-none-any.whl
Collecting six>=1.5 (from python-dateutil->pandas)
Using cached six-1.11.0-py2.py3-none-any.whl
Installing collected packages: numpy, six, python-dateutil, pytz, pandas
Successfully installed numpy-1.14.0 pandas-0.22.0
python-dateutil-2.6.1 pytz-2017.3 six-1.11.0
(Tutorial) Bradleys-Mini:bin BradleyPatton$

The following command will open a Python interpreter command line.  I will import our new pandas library and check the version. Version 19 is my global pandas version, but as you see from the terminal output, the version used in our Tutorial virtual environement is 22.

$ python
(Tutorial) Bradleys-Mini:bin BradleyPatton$ python
Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
>>> import pandas
>>> pandas.__version__
u’0.22.0′
>>>

This tutorial should get you started with Virtualenv.  I have added the link to the Virtualenv page that can assist with some in depth configuration using parameters and configuration settings that can be used in special circumstances.

References

https://virtualenv.pypa.io/en/stable

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

How to Create and Manage Python Virtual Environments

It is pretty common to see Python developers installing and upgrading packages from standard and non-standard sources to...
29/12/2020

Python Matplotlib Tutorial

In this lesson on Python Matplotlib library, we will look at various aspects of this data visualisation library which we...
29/12/2020

Collections in Python

Python collections are just containers which can contain data objects of various data-types inside them. Each collection...
28/12/2020
Bài Viết

Bài Viết Mới Cập Nhật

Mua proxy v4 chạy socks5 để chơi game an toàn, tốc độ cao ở đâu?
18/05/2024

Thuê mua proxy Telegram trọn gói, tốc độ cao, giá siêu hời
18/05/2024

Thuê mua proxy Viettel ở đâu uy tín, chất lượng và giá tốt? 
14/05/2024

Dịch vụ thuê mua proxy US UK uy tín, chất lượng số #1
13/05/2024

Thuê mua proxy Việt Nam: Báo giá & các thông tin MỚI NHẤT
13/05/2024