Search code examples
pythonpython-venv

Unable to change the default version of Python in the virtual environment


I want to create a virtual environment with Python version 3.9. I am using Windows11 operating system. I found various python version in the folder C:\Users\user1\AppData\Local\Programs\Python. The python versions are as follows enter image description here

Now if I want to create a virtual environment following the command python39 -m venv myvenv

I received the error message 'python39' is not recognized as an internal or external command, operable program or batch file. enter image description here

I also tried another way to create a virtual environment, that did not work either

How can I solve this?

Thank you.

enter image description here


Solution

  • You are using Windows, so you can utilize the Python Launcher which was included in Python 3.3.

    Example:

    py --list
     -V:3.12          Python 3.12 (64-bit)
     -V:3.11 *        Python 3.11 (64-bit)
     -V:ContinuumAnalytics/Anaconda39-64 Anaconda 2022.10
    

    With this command you can see that I have 3 version of Python installed in the Windows environment. To make a virtual environment using 3.11:

    py -3.11 -m venv myvenv
    myvenv\Scripts\activate
    
    (myvenv) C:\Users\Andy>python --version
    Python 3.11.5
    

    This command would have worked the same way without the -3.11 because 3.11 is my default (it has the asterisk in the --list output)

    To utilize a different version of Python you need to change the parameter passed to the command

    py -3.12 -m venv myvenv1
    myvenv1\Scripts\activate
    
    (myvenv1) C:\Users\Andy>python --version
    Python 3.12.3
    

    For your example, you can pass 3.9, because it's in your --list output