Why We Need virtualenv
In many cases the Python environments used by projects differ — not only between Python2 and Python3,
but also between library versions; for example BeautifulSoup has versions 3 and 4. After installing Python
on our machine, sometimes we don’t want our Python environment polluted, and we also want the local environment
to match the server environment, including the Python version and library versions.
Different languages also provide different “container” or “package management” forms. Package management:
Pythoncan userequirements.txt,Nodehas npm’spackage.json,JavahasMavenandGradle— these package managers make environment setup especially simple.Containers:
Pythonhasvirtualenv,Nodehas npm’snode_modules, and there is also the recently popularDocker— these containers isolate the local environment from the development environment.Whether in “container” or “package management” form, the goal is ultimately to unify code development or environments to some degree. From a slightly higher perspective, these tools exist to simplify development. Don’t put the cart before the horse — code quality is what really matters.
Installing and Basic Usage of virtualenv
There are many ways to install
virtualenv. I useArchlinux, where it can be installed simply viapacmanor Python’spip. OtherLinuxdistributions have their own methods; worst case you can install from the source package.Using
virtualenv
1 | virtualenv2 venv # create a Python2 environment; virtualenv3 creates a Python3 environment |
After running this command, a venv folder appears in the current directory; check it with ls -al.
- Activate the environment
1 | source venv/bin/activate |
This command updates the current Python environment. After running it, 
you can see the (venv) marker in front of PS1, showing that we are now using the newly created environment.
At this point, run the python command to see that the interactive shell environment is now different.
Using virtualenv Together with requirements.txt
If
virtualenvprovides the ability to quickly create a cleanPythonenvironment, thenrequirements.txtprovides the ability to quickly import a development environment.
Using
requirements.txtWe use
requirements.txtto letpiphandle importing libraries. After getting a project’s source code,
if it contains a requirements.txt, we can import the libraries like this:
1 | pip install -r requirements.txt |
Of course, preferably inside an environment already created with virtualenv.
- Creating
requirements.txt
When we start a new project we always use some libraries. In a virtualenv environment, the libraries
in our environment are exactly what we need, so export them like this:
1 | pip freeze > requirements.txt |
After exporting, a requirements.txt file is created in the current directory, similar to:
1 | appdirs==1.4.0 |