Sometimes, you need to work on different versions of a programming language and switch back and forth between the interpreters.
Install Python Versions – If Not Installed Already
First, you have to install the python versions that you want to work on your pc.
You can either download and install the Python from the official site or use the visual studio installer.
Below we use the later one, assuming the visual studio code is already installed on your computer. If VSC is not ready, check out this installation guide.
So we will go ahead and install Python 2.7 and Python 3.7.
- Use the search bar in Windows and run “Visual Studio Installer.”
- Click on Modify Button
- Click on Python Development in the Workload tab
- Choose the Python versions to install
- Click Modify
The install will take a while, depending on the components you have chosen to install.
How to switch Interpreter in VSC
Now, we are ready to talk about how we can switch interpreters from VSC. We need to open the Command palette to change the interpreter.
After Visual Studio Code is opened, use one of the methods below to trigger the command palette.
- Either click on the Menu and Command Palette or use the shortcut CTRL+SHIFT+P
- The command palette will be displayed on top of VSC.
- Type the command “python select int…” and choose the “Python: Select Interpreter” from the list.
- Choose the language option you prefer
An even shorter way is to use the text at the bottom left corner, displaying the current active python version. When you click on this text, it will open the command palette and list all the python versions available in your environment. Again, just click on the version you want to work on.
How to Run Different Python Versions in Terminal Window
In our case above, we have two python versions installed on our system. If we run the command “python hello.py” from the terminal window, the system will always run the same interpreterif we don’t explicitly define the full path of “python.exe”.
Which one of the python versions run depends on the which one is listed first in environment variables? In other words, the one that Windows OS finds first will take precedence to compile the code.
To run the python 2.7 interpreter, we must use the full path.
If we run the command
python, depending on which version path is listed first in environment variables, that would take the precedence to run the code.
python c:\pythoncode\hello.py – python 3.7 will compile the code.
One approach to solve this could be changing the file name of “exe” for both interpreters (or just one of them).
- Go to python 2 directory and change the
- Set the system Path environment variable to python 2 folder path (if already not set)
If you set the environment variable, you need to restart the windows for the path variable to be active.
Now, we can run whichever version we want from any command prompt.
To run Python 2 interpreter, type:
To run same code with version 3 from the terminal window, type: