Dev note: 20230727 Tips for building virtual environments

Question

with venv

venv is the most recommended way of managing virtual environment since Python 3.5, it is a module within the Python Standard Library, so you don't have to install a third party package.

Install another version of Python you need

By using the following prompt, anyone could install python with a specific version. 3.x means the specific version of python.

sudo apt install python3.x

Create a new directory and build the venv

In the following prompt, [project dir] is the directory where stores your project, and [venvname] is an arbitrary virtual environment name you would like to give.

cd [project dir]
python3.x -m venv [venvname]

Activate the virtual environment

NOTE: In fact, when creating a virtual environment with venv, it has created a folder in project directory in order to store the packages. So the folder structure should be like:

|--[project dir]
	|-- source 
	|-- models 
	|-- [venvname]
		|-- bin 
		|-- ...
	...

Make sure that you have already in the project directory [project dir], then prompting as the following:

source [venvname]/bin/activate

Deactivate and delete virtual environment

You can deactivate the virtual env with a single prompt.

deactivate 

You can also simply delete it with Linux delete prompt (still, make sure you are already in the project directory and deactivated the virtual env). All the files including .bin will be deleted.

sudo rm -rf [venvname]

with conda

If you want to use the magic of managing packages, namely, conda. It is necessary to install Anaconda first.
Ref: How To Install the Anaconda Python Distribution on Ubuntu 22.04 | DigitalOcean

Check installed packages

conda list

Check exited virtual envs

conda env list
conda info -e

Create env with specific python version

Unlike venv, you don't have to locate to the project directory to create a virtual environment.

conda create -n [venvname] python=x.x

Activate virtual env

conda activate [venvname]

Install new packages in specific env

You could also install some packages you need in different virtual environment by specifying the environment name.

conda install -n [venvname] [package]

Delete virtual environment

conda remove --name [venvname] --all
# If you just want to delete some of packages in a specific env
conda remove --name $[venvname] $[package]