Virtual Environments allow us to create and switch between different projects, keeping each project’s dependencies isolated.
The following example will be based on a version of Python 3 installed from Homebrew on MacOS.
To install Homebrew, you can find the installation instructions here. Once it’s installed simply run
brew install python3 in your terminal.
virtualenv can be installed using pip (pip3 if you’ve installed Python 3 with Homebrew):
pip3 install virtualenv
First, need to create a new folder for our project and cd into it.
Now we can create our isolated virtual environment which will be placed into a folder named
virtualenv -p python3 venv --always-copy
Notice, a couple of flags were used here. The
-p specifies a Python version. In this case, the default Python interpreter will be the OS installed version rather than the Homebrew version. The second flag,
--always-copy, will copy the files to your venv directory rather than create symbolic links. This is necessary because your virtual environment won’t break the next time you update the Python version with Homebrew.
Once our virtual environment is created, we need to activate it to change our Python source inside the terminal:
When this is activated properly, you should see
(venv) on the left side of the command prompt. In addition, if you enter the command
which python, you should see the path to your newly created venv directory in your project.
A common alternative is to keep all the virtual environments in a separate, single place outside the project (i.e. ~/.virtualenvs). I generally prefer to keep them in the root folder of each project. Using this method, you don’t need to worry about adding it to your .gitignore file.
- you should add venv to your .gitignore
- enter “deactivate” in your terminal to exit out of your virtual environment
- save a list of your requirements
- consider a tool, such as autoenv, to automatically activate your virtual environment each time you enter it
Saving a list of your requirements is important in case your virtual environment gets destroyed. If multiple people are working on the same project, this will also help ensure everyone has installed the same version of each dependency.
# After installing dependencies:
pip freeze > requirements.txt
# install same packages on a different machine
pip install -r requirements.txt
Posted in python