Python venv

Python Virtual Environments

  • If you're running myltiple python project on your computer, you may want use a tool that handles python virtual environments, for reasons such as:
    • be able to install different libraries and modules for each project
    • Use different versions of python for different projects
  • This is especially important if you plan to encapsulate your code in a docker image, because you'd want to control all of the software your project depends on.

Virtual environment options

There are many:

Using venv

  • The venv python module is the built-in virtual environment tool for python.
  • "When used from within a virtual environment, common installation tools such as pip will install Python packages into a virtual environment without needing to be told to do so explicitly",
    or in other words, inside you project directory, not somewhere in you OS environment.
  • To create a new virtual environment:
    • You only need your python installation
    • Go to your project main directory (proj1 in my example), and create a virtual environment in it:
1python3 -m venv myenv
  • My virtual environment is called myenv:
1$ ls -l
2total 4
3drwxrwxr-x 5 osboxes osboxes 4096 Feb  4 02:57 myenv
4$  
  • To work, it should be activated:
1$ source myenv/bin/activate
2(myenv) $ 
3(myenv) $ 
  • To deactivate:
1(myenv) $ 
2(myenv) $ deactivate
3$