While learning Flask, one of my biggest challenges has been wrapping my head around how virtualenv works. This blog post is really just to lay out my basic understanding of how it works. One of my main sources of information has come from this fantastic blog post by Jamie Matthews.
Here’s some of the more important points that needs to be understood before understanding virtualenv:
pip
is a tool that installs packages from the Python Package Index (aka PyPI; the Cheeseshop).- PyPI is an online repository with over 60,000 packages included in it. Whenever you use
pip
to install a package, it gets the package from here.
- PyPI is an online repository with over 60,000 packages included in it. Whenever you use
- pip, by default, installs packages to Python’s
site-packages
directory. Anything installed in Python’ssite-packages
directory can be imported by any of your programs. virtualenv
creates a complete copy of everything needed to run a Python program, including a copy of thepython
binary itself, a copy of the entire Python standard library, a copy of thepip
installer, and (crucially) a copy of thesite-packages
directory
How do you install virtualenv?
- For Windows: make sure that your Path is set to access commands from your Python directory, or alternatively, just navigate to your Python directory.
- Run
pip install virtualenv
How do you setup an environment?
- Change your directory into the root of your project directory, and then use the
virtualenv
command-line tool to create a new environment:virtualenv venv
- The
env
part is just the name of the directory you want to store the environment in. You can changevenv
to anything, but it is standard practice to keep it namedvenv
- One of the folders created by
virtualenv
is calledScripts
. Some scripts are created in this folder when you first created your environment. Of note are theactivate
anddeactivate
scripts. Run these to activate and deactivate your environment. - Cool note: you need to specify the path when you run
activate
(by entering something like:c:\myProject\env\Scripts\activate
) but you don’t need to specify the path when you rundeactivate
– runningactivate
makes the association for you. Convenient!
Here are some other resources on basic virtualenv
functionality:
- I got a lot of cool hints from this StackOverflow page.
- This official documentation page on
virtualenv
And if you are interested in virtualenv
with PythonAnywhere, these threads might help as well: