Why use a virtual environment?

Using virtual environments for python projects is important so that you can have isolated projects on the same machine. What does this mean? You might have a project that requires python 2.7 and another project that requires python 3.5. By developing inside virtual environments you can easily isolate those projects to use a specific python version.

You can also isolate the packages that are required for a given project. Imagine you have multiple projects using django. One project requires django 1.8 and another project requires django 1.9. You need to have different environments so that you can require those different versions of django.

How do I create a virtual environment?

Most projects now use Python 3, so I'll be going through this example using python 3. For Python 2 you'll need to use a program called virtualenv.

Virtual environments are so important, that it's built right into Python 3. If you don't already have python 3 installed, you'll need to install it at python.org.

Go to the directory you'd like to create the environment in, and then in terminal run $ pyvenv ENV_NAME. Replace ENV_NAME with what you'd like your project environment to be called. That will create a new environment with a folder name of what you gave in the ENV_NAME argument. Go into that directory and you'll see various other folders, which were created with your environment and for the most part you won't touch.

Our environment is created, but we still need to activate it. Activating it lets your terminal know that you want to be using that environment and the packages installed to that environment. Assuming you're still in your environment directory, run $ source bin/activate and you'll have your environment activated.

Now we can create our django project by running $ pip install django, which will install the latest django package. After a few seconds that will finish installing and you can create a new django project by running $ django-admin startproject MYPROJECT. That will have created a folder with the name of whatever you provided for your MYPROJECT argument.

And there you have it, a new django project in its own isolated environment. If you want to get out of the enviornment, you can simply run $ deactivate.