Virtual Envs
Note: you don’t have to use virtual envs if you
don’t want to. You can just keep on happily installing (system-wide) deb
packages via apt, and keep on using
python3 -m pip install --user pkg-name
to install
everything else into your home dir, if you like.
Executive Summary: If you want to use virtual envs,
do so using the built-in venv
module.
As of the current Python 3, the venv module is in the standard
library. You use it like python3 -m venv ...
(see examples
below).
Note, I use the term “venv” here to mean (1) the venv module, and also (2) as a shorthand for “virtual environment”.
Work with venvs like so:
$ cd ~/py-venvs
$ python3 -m venv foo-env # Makes the ./foo-env directory for you.
$ cd foo-env
# In ./bin, we have `pip{,3,3.6}`, `python{,3,3.6}` --- all are Python 3 versions.
$ . bin/activate
# Prompt changes.
(foo-env)...$ which pip
#=> /path/to/foo-env/bin/pip
# {work, work, work}
(foo-env)...$ which python
#=> /path/to/foo-env/bin/python
(foo-env)...$ python -V # This is on Debian Testing.
#=> Python 3.6.6
(foo-env)...$ pip install SomeThing # Installs into this venv's tree.
(foo-env)...$ pip install --upgrade SomeOutdatedThing
(foo-env)...$ pip install --upgrade pip # Ugrade this venv's pip.
(foo-env)...$ cd /path/to/my-proj
(foo-env)...$ # work work work
(foo-env)...$ # ...
(foo-env)...$ deactivate
# prompt now back to normal
$
If you’d like to upgrade pip itself (if it’s not already the newest version):
pip install --upgrade pip
See pip help
for general help, and
pip help <command>
for help on a particular command.
Pip docs are at https://pip.pypa.io/en/stable/.
Once you have a venv set up with the packages you want, you can save that config like so:
(foo-env)...$ pip freeze > requirements.txt
then later, with a fresh venv, you can install all of those modules just like you had them before:
(foo-other-env)...$ pip install -r requirements.txt
Unrelated or don’t-use:
- pyvenv — a deprecated script. Use
python3 -m venv
instead. (BTW, note that pyenv is not the same thing as pyvenv.) - virtualenv: as of Python3, a subset of this comes pre-packaged as the “venv” module in the standard library.
- Legacy: easy_install, ez_setup.py, eggs, Distribute, distutils2, get-pip.py