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:
pipis 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
pipto 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-packagesdirectory. Anything installed in Python’ssite-packagesdirectory can be imported by any of your programs. virtualenvcreates a complete copy of everything needed to run a Python program, including a copy of thepythonbinary itself, a copy of the entire Python standard library, a copy of thepipinstaller, and (crucially) a copy of thesite-packagesdirectory
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
virtualenvcommand-line tool to create a new environment:virtualenv venv- The
envpart is just the name of the directory you want to store the environment in. You can changevenvto anything, but it is standard practice to keep it namedvenv - One of the folders created by
virtualenvis calledScripts. Some scripts are created in this folder when you first created your environment. Of note are theactivateanddeactivatescripts. 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– runningactivatemakes 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: