Explain Codes LogoExplain Codes Logo

Use different Python version with virtualenv

python
virtualenv
python-versions
environment-management
Anton ShumikhinbyAnton Shumikhin·Sep 25, 2024
TLDR

To use a specific Python version in a virtualenv, specify the python executable during creation:

virtualenv -p python3.x envname

Here, python3.x is your target Python version and envname is your virtual environment's name.

For Python 3.8:

virtualenv -p python3.8 envname

Activate it:

source envname/bin/activate

Your virtualenv now runs Python 3.8.

Check available python versions

Before diving into a virtual environment, make sure you've got the right Python version installed. You can do this by running one of these commands:

  • On Linux/Mac:

    which python # or which python3
  • On Windows:

    py -0p

These commands spit out paths to the Python interpreters. If you don't see the version you want, you'll need to install it first. Missing Python versions are like missing socks - you know they're there somewhere, you just can't find them!

Building Python from source

Sometimes, like an overenthusiastic pizza maker, you need more control over your ingredients. You can build Python from source to get exactly what you want.

  • Download and extract the Python source code:

    wget [Python source URL] tar -zxvf [Python source file]
  • In the source directory, set the installation path:

    ./configure --prefix=$HOME/.localpython
  • Compile and install your custom Python:

    make make install

Now you've got Python exactly the way you like it! Enjoy the smell of freshly baked Python goodness.

Managing environments like a boss

Give pyenv a try for a more delightful experience managing multiple Python versions. It provides easy commands to install and switch Python versions. Combined with virtualenv via the pyenv-virtualenv plugin, it's like a Swiss Army knife for Python environments.

Always remember pyvenv is the old cool. From Python 3.6 onwards, it's recommended to use python -m venv.

Organize your tools

  • Maintain clear separation between different environments:

    mkdir projectA_env virtualenv -p python3.6 projectA_env
  • Activation for Windows users:

    .\envname\Scripts\activate
  • Keep your tools sharp and updated

    pip install --upgrade virtualenv #because nobody likes a rusty tool!
  • Mirror your production environment for predictable deployment outcomes:

    virtualenv -p python3.6 prod_env #because surprises are better left for birthdays!