Mastering Python for Networking and Security
上QQ阅读APP看书,第一时间看更新

Using virtualenv and virtualwrapper

When you install a Python module in your local machine without using a virtual environment, you are installing it globally in the operating system. This installation usually requires a user root administrator and that Python module is installed for every user and every project.

At this point, the best practice is install a Python virtual environment if you need to work on multiple Python projects or you need a way to work with all associated libraries in many projects.

Virtualenv is a Python module that allows you to create virtual and isolated environments. Basically, you create a folder with all the executable files and modules needed for a project. You can install virtualenv with the following command:

$ sudo pip install virtualenv

To create a new virtual environment, create a folder and enter the folder from the command line:

$ cd your_new_folder
$ virtualenv name-of-virtual-environment

For example, this creates a new environment called myVirtualEnv, which you must activate in order to use it:

$ cd myVirtualEnv/
$ virtualenv myVirtualEnv
$ source bin/activate

Executing this command will initiate a folder with the name indicated in your current working directory with all the executable files of Python and the pip module that allows you to install different packages in your virtual environment.

Virtualenv is like a sandbox where all the dependencies of the project will be installed when you are working, and all modules and dependencies are kept separate. If users have the  same version of Python installed on their machine, the same code will work from the virtual environment without requiring any change.

Virtualenvwrapper allows you to better organize all your virtually-managed environments on your machine and provides a more optimal way to use virtualenv.

We can use the pip command to install virtualwrapper since is available in the official Python repository. The only requirement to install it is to have previously installed virtualenv:

$ pip install virtualenvwrapper

To create a virtual environment in Windows, you can use the virtualenv command:

virtualenv venv
When we execute previous command, we see this result:

The execution of the virtualenv command in Windows generates four folders:

In the scripts folder, there is a script called activate.bat to activate the virtual env. Once we have it active, we will have a clean environment of modules and libraries and we will have to download the dependencies of our project so that they are copied in this directory using the following code:

cd venv\Scripts\activate
(venv) > pip install -r requirements.txt
This is the active folder when we can find the active.bat script: