How should I set the default Python version in Windows


Question

I installed Python 2.6 and Python 3 on Windows 7 and set environment variable: path = d:\python2.6.

When I run python in cmd, it displays the python version is 2.6, which is right!

But when I wrote a script in a bat file and ran it, the displayed python version was 3.1.

What is wrong here?

The script code in bat file:

import sys
print (sys.version)
1
48
10/22/2016 7:44:12 PM

The last Python you install that registers itself in the environment is the default (I can't remember the exact wording in the installer, but it is the first option). There are a number of settings so to make sure they are all registered consistently just reinstall the version you want to be the default.

If you want to install another version but don't want it as the default just disable the registration option during installation.

Edit (May 19, 2012)

Starting with Python 3.3, the Python installer installs Python Launcher for Windows. This program (py.exe) is associated with the Python file extensions and looks for a "shebang" comment to specify the python version to run. This allows many versions of Python to co-exist and allows Python scripts to explicitly specify which version to use, if desired. If it is not specified, the default is to use the latest Python 2.X version for the current architecture (x86 or x64). This default can be customized through a py.ini file or PY_PYTHON environment variable. See the docs for more details.

Just make sure the Python 3.3 is the last Python installed that registered itself with Windows. If other versions of Python are installed later be sure not to register them with the environment, so the launcher will remain the default.

Here's how to check if the launcher is registered correctly from the console:

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Windows\py.exe" "%1" %*

Above, .py files are associated with the Python.File type. The command line for Python.File is the Python Launcher, which is installed in the Windows directory since it is always in the PATH.

For the association to work, run scripts from the command line with script.py, not "python script.py", otherwise python will be run instead of py. py.exe can also be run with switches to force a Python version:

py -3 script.py    # force latest Python 3.X version to be used.

Additionally, add .py;.pyw;.pyc;.pyo to the PATHEXT environment variable and then the command line can just be script with no extension.

48
5/19/2013 8:24:41 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon