Python venv for pip
By Erik Letson, Aug 20th, 2020 (blog index)
I never install Python pip packages globally on Linux. Doing so is dangerous because it goes over the head of your package manager, and it can easily introduce conflicts. However, I often find myself downloading Python projects and having to install packages to run them. So what is the best way to handle this? The answer is venv, the virtual environment module for Python.
I'm not going to go in-depth on venv here (you can refer to the documentation if you want more info on the subject). Instead, I am just going to demonstrate a general use-case for venv that I encounter whenever I need to (a). use a Python program that takes external packages; or (b). write a new Python program that will use an external package.
The example I am going to be using is the PyGame package. Let's say I am starting a new project that needs the PyGame package to be installed, but I don't want to install it globally with pip. The best solution to this would be to create a virtual environment, enter it, install PyGame there, then do all work on the project in the context of that environment. If I want to leave the environment, I am able to, and I can enter it again (and have access to any installed packages) at any time. Here is how this is done:
- Create an environment directory in your project (named env in this example): mkdir env
- Create a virtual environment in the new directory: python3 -m venv env
- Enter this virtual environment: source env/bin/activate
- Install any needed packages with pip (PyGame in this example): pip install pygame
- Do any work on the project in this context
- To leave the virtual environment: deactivate
- To re-enter the virtual environment: source env/bin/activate
That's all there is to it. This is the safest, easiest, cleanest way to use pip in Linux. Doing this, you can have access to the newest versions of packages as offered by pip, and yet never run into a situation where you introduce package conflicts to your system by installing anything with pip globally.