How to Change Python Version

Muhammad Waiz Khan Feb 02, 2024
  1. Change Python Version by Replacing the Commands
  2. Specify Python Version in the Script File
How to Change Python Version

In this tutorial, we will look into different ways to change or set specific version of Python to execute programs. As there can be multiple versions of Python at a time on a computer, suppose we have Python version 3.xy installed on our computer and want to use it for all the tasks.

As Python 3 is not backward compatible for Python 2 programs, many programs may still require Python 2, and that is why it is not a good idea to change the default Python version to Python 3. Therefore we can use the python3 command to execute Python 3 scripts and the python command to execute Python 2 scripts.

We can also do the following things to use Python 3 instead of Python 2 when the python command is used, or Python scripts are executed.

Change Python Version by Replacing the Commands

One easy way to use the latest version of Python 3 with the python command is by replacing the python keyword with python3. We can use the alias command in Linux-based operating systems and the doskey command in Windows to replace python with python3. So, whenever the python command is used, it will be replaced by python3, and the latest version of Python 3 available on the computer will be used to execute the script.

The below examples demonstrate how to replace the python with python3 in Linux-based operating systems and windows.

Linux:

alias python=python3

Windows:

doskey python=python3

Specify Python Version in the Script File

As the python command is used by Python 2, and it is not recommended to change the default python version as many programs and scripts can still need Python 2 to run. Another way is to specify the version of Python we want to execute within the Python script file. We can specify the Python version to execute the script file by mentioning the Python version on the script file’s first line.

We can use the following text as the first line of the script file to use the latest version of Python 3 available on the computer to execute the Python script.

#! python3

We can also specify the Python version of our choice by putting the following text as the first line in the Python script file.

#! python 2.5

Suppose the specified version is available on the computer. In that case, the operating system will use that version to execute the Python script or otherwise will return a similar error as shown below.

Requested Python version is not installed