Installing Python modules with Virtual Environment

Last modified by Niko-Ville Koljonen on 2024/02/16 11:35

Installing missing Python modules without sudo rights using virtual environment.  First, create a virtual environment, if you don't want to use an existing one.  Here 'name_of_your_venv_dir' is the new directory, hosting the created virtual env.

python3 -m venv name_of_your_venv_dir

Then activate the new virtual environment, and update the tools.  (Start from this step, if you already have an existing virtual env which you want to use)

. ./name_of_your_venv_dir/bin/activate
pip install -U pip

Now you can install the missing Python modules by:

pip install <name_of_package>

Now, whenever you want to use your newly isntalled modules in a new session, you have to activate the virtual env by

. ./name_of_your_venv_dir/bin/activate

The benefit of using virtual environments is that they are separate from your system files.  So, if you mess your virtual environment, you can just remove the directory and create a new one, i.e. your system will be safe even if pip does something unexpected.  Also, if you have several projects with conflicting module dependencies, you can create separate environment for each of them.