packagehowto/venv.md
2024-04-29 14:07:30 +02:00

3.0 KiB

Why and how to use virtual environments?

What is a virtual environment?

  • A venv is seperated from your system packages / software, such as firefox, thunderbird, etc.
  • Packages that are installed cannot talk to system packages and vice versa -> you know what you use because you have to explicitly install all packages that your project requires.
  • They can be build and destroyed easily and quickly to test different versions of packages (or even python itself!).

How to build a venv?

  • PEP405 (=python style guide) virtual environments should be named "venv" or ".venv".

To create one, run:

python -m venv <name> # e.g. venv or .venv

You should now see a new directory in your current working directory called "venv" or ".venv".

To activate it, run this on linux or macos:

source <name>/bin/activate

On windows, you can run

./<name>/Scripts/Activate.ps1

You should now see an indicator in your shell prompt such as:

(venv) user@host:~/path/to/your/project

It is active as long as you do not explicitly deactivate it or close the shell. You can now pip install <package> as you normally would. To check which python version it uses, you can run this on linux/macos:

which python3 && which pip

Both paths should point to your virtual environment in the project directory.

To deactivate, simply run on linux/macos/windows:

deactivate

What we have now seen all comes with python but there are tools that make this more convenient: What if you also want to try another pyhton version? Or use the same venv in multiple projects? For this, there is pyenv:

venv pitfalls

  • You cannot move or rename any directory inside the path to your project directory or the venv breaks. You can rename a folder inside the project directory as long as you dont change the path to the venv.
  • You cannot use the venv for multiple projects

pyenv fixes this:

Using pyenv / pyenv-virtualenv

Use pyenv for managing python versions and pyenv-virtualenv for a slightly easier way of interacting with venvs.

To download another python version (without destroying your system), simply run:

pyenv install python3.12

To see which versions are installed, you can run

pyenv versions

To set this version as the default in a specific directory (and all its subdirectories), run:

pyenv local 3.12

Now you can either use the tutorial above to create a standard venv or use pyenv-virtualenv like this:

pyenv virtualenv 3.12 <name>

Now you can activate it by pyenv activate <name> or use it as the standard in the current and subdirectories with

pyenv local <name>

The convenient thing is, that this venv will always be automatically activated when you enter the directory. If you do this in multiple directories, you can have the same venv for multiple projects.

There are some alternatives to pyenv such as