Python Notes and Examples
← prev | next →     Top-level ToC     /virtual-envs.html     (printable version)

As of the current Python 3, the venv module is in the standard library. You use it like python3 -m venv ....

I use the term “venv” here to mean: (1) the venv module, and (2) as shorthand for “virtual environment”.

(On Debian, with the current Python 3.5, to have the venv module work right you’ll need to first apt install python3-venv.)

Work with venvs like so:

$ python3 -m venv foo-proj  # Makes the ./foo-proj directory for you.
$ cd foo-proj
# In ./bin, we have `pip{,3,3.5}`, `python{,3,3.5}`  --- all are Python 3 versions.
$ . bin/activate
# Prompt has changed.
(foo-proj)...$ which pip
#=> /path/to/foo-proj/bin/pip
# {work, work, work}
(foo-proj)...$ which python
#=> /path/to/foo-proj/bin/python
(foo-proj)...$ python -V  # This is on Debian Testing.
#=> Python 3.5.3+
(foo-proj)...$ pip install SomeThing      # Installs into this venv's tree.
(foo-proj)...$ pip install --upgrade SomeOutdatedThing
(foo-proj)...$ pip install --upgrade pip  # Ugrade this venv's pip.
(foo-proj)...$ 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/.

Note, you don’t have to stay or work in the venv directory. Though, if you’ve created a venv for a particular project, it may make sense to keep your project files within that directory.

Once you have a venv set up with the packages you want, you can save that config like so:

pip freeze > requirements.txt

then later, with a fresh venv, you can install all of those modules just like you had them before:

pip install -r requirements.txt
* * *

Unrelated or don’t-use:

  • pyvenv — just do python3 -m venv instead
  • virtualenv: OLD (Python 2). Subsumed by venv module in Python 3.
  • Legacy: easy_install, ez_setup.py, eggs, Distribute, distutils2, get-pip.py
  • pyenv: This is not pyvenv.