>

Python Virtual Environment

Python encountered a problem, many packages would be needed/required for a single package.

Thus the system Python (global installation) would get cluttered.

It also made distribution a big nightmare.

That’s where the Python Virtual Environment (pyvenv or venv) became invaluable.

With a pyvenv every package/module is stored local to the virtual environment.

You can follow this link to the official venv documentation.

Making a Virtual Environment

python3 -m venv . <env_name>

This also means you could destroy your pyvenv and rebuilt it, as it’s simply a directory.

Activating the Virtual Environment

# Unix/Linux
. <env_name>/bin/activate

Once active, all pip install commands instead of installing to the system python, it installs to the venv.

You’ll need to re-activate the venv everytime you close your shell/terminal.

Saving installed packages

# Unix/Linux
pip freeze > requirements.txt

This will save all the installed packages and their exact version info into the file.

Loading packages from requirements.txt

# Unix/Linux
pip install -r requirements.txt

This will load all the packages and their exact version info from the file into the venv.


2023-10-24