Virtual environments in python
11 Apr 2022
This gets added to the very long list of programming techniques I wish I’d got into earlier (git, unit testing, understanding debuggers… ad inf)
Python is my go to language for prototyping my ideas, or, putting less of a old-wise-man spin on it: Python is what I reach for when I think “This should be easy”, before realising it’s a big project and probably would have benefitted from a different approach.
Virtual environments: You usually end up installing loads of python dependencies via pip which you only use for that one project. This is where virtual environments come in. A virtual environment lives in your working folder and holds all the pip packages you’re using just for this project.
create a new virtual environment (henceforth venv) like This:
python3 -m venv [the name of your venv (usually I call it venv)]
That’s assuming you want to be using python 3.
then activate the venv:
source ./venv/bin/activate
At this point you may see ‘venv’ appear on your command prompt depending on what you’re using. OhMyZsh will display it along with other nice things like git status.
Now whenever you install anything via pip it will exists only in your local venv and not clutter or mess up anything else on your system. Also when you run python it will be the version of python you invoked when you created the venv, so you don’t need to keep typing python3, just type python instead.
To deactivate the venv just type
deactivate
Then cd to another python project and activate the venv for that one and you can pick up where you left off with that project running a completely different set of dependencies.
Git and Venvs
Probably you don’t want to add your venv folder to git (or push it to a remote). So add venv to .gitignore
echo venv >> .gitignore
and run
pip freeze > requirements.txt
And add this file to your git repo so you never loose track of what pip packages are needed.