This is the second post in a dummies guide to getting stared with Python, Django, & MySQL on Windows 7.
- Part 1: installing Python, pip, and iPython
- Part 2: virtual environments (you are here)
- Part 3: making iPython work in virtual environments
- Part 4: installing Django
- Part 5: installing MySQL
Part 1 of the Python, Django, and MySQL on Windows 7 tutorial covered the basics: installing Python and some package management tools.
Set up virtual environments
We saw how easy it is to install Python packages such as iPython. Just run the install command, and everything you need goes into Python’s site-packages folder. But what if different projects require different packages or even different versions of the same package? Of what if you have a project that requires an older version of Python?
If you’re planning to work on multiple applications, you need virtual environments to prevent a big mess of dependencies gone awry. Each virtual environment has its own installation directories, separate from other environments.
Virtual environments are brought to you courtesy of the virtualenv package. To install the package and create a virtual environment:
- Open a command window.
- Install virtualenv by typing
pip install virtualenvand waiting for the successfully installed virtualenv message.
- Create a folder to hold your virtual environments (for example, c:\virtualenvs) and cd it (it’s easier if there are no spaces in the folder name).
- Create a new virtual environment by typing
virtualenv --no-site-packages [environment name]. The output will look something like this:
- Look at your virtual environments folder. You should now see a sub-folder with the name of your new environment.
- Create another environment, just for fun:
virtualenv env2 --no-site-packages
- Activate a virtual environment by running its activate script, located in the environment’s Scripts folder. In this example, the command is
- The command prompt is now preceded by the environment name–that’s how you know the environment is active. The activate script also takes care of adding the virtual environment’s scripts folder to the beginning of your path.
- Now that a virtual environment is active, try installing a package (we’ll use python-twitter as an example):
pip install python-twitter
- Once the package is installed, you can see that it’s in the site-packages folder of the virtual environment, but the original Python install and the other virtual environments remain untouched.
- To deactivate the environment, just run the deactivate script in [envrionment name]\scripts\deactivate
Bonus: Virtualenvwrapper is a handy set of extensions for virtual environments. This is a necessary tool if you deal with multiple environments on a daily basis, but it’s not essential right now if you’ll be working in a single environment. The Windows virtualenvwrapper port is here.
Coming next… getting iPython to work with virtual environments.