What does virtualenv do?
virtualenv copies a local python interpreter into a folder and, once activated, prepends its location to your PATH
- meaning that the python executable sitting there will be used to run python code. In essence, that's it.
How can I activate it/check if it is active?
After creating a virtualenv with, for example, virtualenv venv
, you can activate it with with source ./venv/bin/activate
- done.
If you are unsure whether a venv is active, it is usually enough to look at your command line, which will contain its name like so: (venv) user@workstation:~$
. Alternatively, you can run python -c "import sys; print(sys.executable)"
, which will then print the venv's location instead of /usr/bin/python
, or whatever the system default is.
Since many people use PyCharm, follow these instructions to use a venv within your IDE. It is easy and convenient, so if you use PyCharm, I would advice you to handle your venvs with it.
Why would I want all that?
Isolating development environments from each other can save you a lot of headache. Maybe you want to try the newest python dev build without unleashing it on your precious system, maybe you need different versions of python packages for different projects. Keeping the executing environment static as your source code changes is just a very good idea in general.
How do I install a package into a virtual environment?
By default, the tools you need to install packages, setuptools
, pip
, and wheel
are packed into a newly created venv already, and you can just install a package with pip install package_name
. Pay attention to not use sudo, as that will change the executing user to root and bypass the venv-activation.
Some use cases
virtualenv -p pyhton3.7 venv
-- I want to use a python interpreter that is different from my default one, e.g. python3.7
. Needs an installation of said python interpreter on the system!
virtualenv --system-site-packages venv
-- I want to use all the packages that are already installed with the python interpreter that is used in the venv. Useful if you regularly work with big packages like numpy.
virtualenv venv && source ./venv/bin/activate && pip install -r requirements.txt
-- After cloning a project from github (and cd
ing into it), set up a working independent python environment for it.