Explain Codes LogoExplain Codes Logo

How to run multiple Python versions on Windows

python
virtual-environment
python-versions
windows
Nikita BarsukovbyNikita Barsukov·Feb 20, 2025
TLDR

Install each Python version from the official site. Avoid adding to PATH to prevent hiccups. Use the py launcher to specifiy a version:

py -3.8 # for Python 3.8

In your Python files, use a shebang for the preferred version:

#!/usr/bin/env python3.8

Construct virtual environments for specific projects and Python versions:

py -3.8 -m venv project_env project_env\Scripts\activate

Switch versions using pyenv-win or manually update PATH in your command line.

The PATHway to Success

The PATH environment variable is your torchlight in the dark world of multiple Python versions. Ensure there's no global interference. You should be setting the PATH locally within each command console using the Python version of your choice:

set PATH=C:\Python38;%PATH%

Salute batch files for automating environment preparation, acting like your loyal minions. A sample minion (aka batch file setpython38.bat):

@echo off set PATH=C:\Python38;%PATH%

For Encapsulation: Virtual Environment

Virtualenv is your personal assistant for managing project dependencies. It boots and shuts down as per your orders:

py -3.7 -m pip install virtualenv virtualenv my_project_env_37

In command of the correct Python version for your project? Simply activate your environment:

my_project_env_37\Scripts\activate

When it's time to switch jobs or Python versions, use the deactivate command.

Get a Personalized Python Experience

Personalize your command for Python. Configuring the PATHEXT environment variable allows for simple Python file execution. You no longer need to type '.exe'. Just use the script name:

set PATHEXT=%PATHEXT%;.PY python_script

The 'py' launcher has got your back! It adheres to the Python version declared in a script’s shebang line:

#! python3.7 print("Hello from Python 3.7!")

And yes, you can still use symbolic links for quick access to different versions. Isn't that awesome!

mklink /D C:\Python37 C:\Users\<username>\AppData\Local\Programs\Python\Python37

In the 'py' Launcher We Trust

The 'py' launcher for Windows, as bestowed by PEP 397, is your trusted general for version warfare. Use the command-line switches to specify the version:

py -2 # Python 2.x py -3 # Python 3.x py -3.7-32 # Python 3.7 32-bit

Brushing up on PEP 397 guidelines will polish your axes for the Python version battles on Windows.

Project-Specific Configurations to the Rescue

Leverage .bat or .cmd files to encapsulate your environment settings. Your Python version and script execution are no longer global matters, but project-specific protocols:

@ECHO OFF CALL C:\Path\To\Your\Env\Scripts\activate python your_script.py

Double-click the batch file to run your Python delights with all the right environment condiments ("Double, double toil and trouble; Batch file run, and codebase bubble" 😉).