Virtual environments with venv

1 minute read comments

In my previous post I’ve shown, how to create virtual environments with conda. I also explained, why I recommend to work with virtual environments instead with the system interpreter solely. Alternatively to conda, we can also create such virtual environments with Python’s built-in venv command.

img

Creating virtual environments with venv

  1. Open a terminal and change the current working directory (cd) to the location, where you want to install the virtual environment (e.g., the corresponding project folder).
  2. To create a virtual environment, e.g., called “my_test_venv”, type:

      python -m venv my_test_venv
    
  3. We can activate the environment via:

      source my_test_venv/bin/activate
    
  4. We can verify the activation by checking the currently used Python version:

      which python
    
  5. To deactivate an active virtual environment, simply type:

      deactivate
    

Installing packages

Use pip to manage and install packages. E.g., to check, which packages are already installed, use pip list.

Create virtual environments with a specific Python version

The major difference between Python- and conda-generated virtual environments is, that conda downloads and installs the specified Python version as a package into the created virtual environment, while venv relies on the installed Python interpreter(s) on your machine. This means, that you need to install a specific Python version in advance, if you’d like to use it in a virtual environment.

So far I couldn’t figure out, how to specify the desired Python version in the venv command. Here is a solution using the virtualenv package:

  1. If not already done, first install the virtualenv package into your base Python installation:

      python -m pip install virtualenv
    
  2. To create a virtual environment using a specific Python version, type:

      virtualenv --python=<PATH/TO/THE/LOCAL-PYTHON-INTERPRETER/> <PATH/THE/NEW/VENV/>
    

    where

    • <PATH/TO/THE/LOCAL-PYTHON-INTERPRETER/> specifies the path to the local Python installation you’d like to use, e.g., /usr/bin/python3.10, and
    • <PATH/THE/NEW/VENV/> is the path to the location, where you’d like to install virtual environment.

Comments

Commenting on this post is currently disabled.

Comments on this website are based on a Mastodon-powered comment system. Learn more about it here.