Python Notes and Examples

Virtual Envs

Note: you don’t have to use virtual envs if you don’t want to. Just keep on installing apt packages via apt, and using python3 -m pip install --user pkg-name to install the rest into your home dir, if you like.

* * *

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.6, to have the venv module work right you’ll need to first apt install python3-venv.)

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: