loading...

How to run virtual environments with different versions of Python

joeneville_ profile image Joe Neville ใƒป1 min read

Always use a Virtual Environment

๐Ÿฆ‰ It is a wise move to always run your Python projects in a virtual environment.
๐ŸŽˆ Installing the many dependencies that the average Python program requires into your base OS can soon lead to a bloated system.
๐Ÿฑ Better to run a virtual environment per project and keep everything clean and compartmentalized.

Python 2 and Python 3?

  • With that in mind, I had a requirement recently to run a program that required Python 2.7. I was running Python 3.8 on my machine.
  • I realized that a virtual environment itself wasn't going to be enough. By default my virtual environments were all using Python 3.8.

Here's how I approached the problem on Windows 10:

  1. Install Python2.7 from python.org

    Make sure you take a note of where the .exe file is installed. On my Windows machine the path was:

    C:\Python27\python.exe
    
  2. Install the Python package 'virtualenv' using pip:

    pip install virtualenv
    
  3. Create a new virtual environment using the Python 2.7 executable.

    Here the virtual environment is called venv1 and it uses Python2.7.

    virtualenv -p C:\Python27\python.exe venv1
    
  4. Activate the virtual environment.

    .\venv1\Scripts\activate
    
  5. Now if I enter 'python' I can see that I'm using Python 2.7.18 rather than the default 3.8:

    (venv1) PS C:\Users\joe> python
    Python 2.7.18<snip>
    
  6. To create a virtual environment with Python 3.8, I can just run virtualenv without the p flag:

    virtualenv venv2
    

โœจ๐Ÿ‘นโœจ
@joeneville_

Discussion

pic
Editor guide