How to set up virtual environments and manage Python versions in Linux?
For Python development in Linux, it is often necessary to isolate project dependencies and use different interpreter versions, as the system Python should not be touched to avoid operating system failures. The most popular tool for managing Python versions is pyenv, which allows you to install and switch interpreter versions in the user directory without superuser privileges.
To install pyenv, you first need to download the necessary system dependencies for compiling Python from source code using your distribution's package manager. Then, the pyenv repository is cloned into the home directory, and environment variables are configured in the shell configuration file, for example, in bashrc or zshrc.
After configuring pyenv, installing the desired Python version comes down to a simple build command, after which this version can be made global or local for a specific project folder. To create an isolated environment inside a project, the built-in venv module is used, which is launched by the command to create the environment directory followed by its activation via the activation script file.
Activating the virtual environment modifies the PATH environment variable, directing all python and pip calls inside the created folder with isolated libraries. To exit the environment, simply enter the deactivation command, and for full automation of the development process, third-party project managers such as Poetry or Pipenv are often used, combining version control, dependencies, and building into a single interface.