Ad

Using #!python2 Not Working To Run Under Python 2

- 1 answer

I have both Python 2 and 3 installed on my machine running Windows.

I am running a program via cmd which has the command #!python2 at the very top of the code, and i want that to run in Python2.

It was my understanding that the having #!python2 on the first line would force Python to use Python2. Instead it uses Python3 [and hence the line 'print helloresults in the errorSyntaxError: Missing parentheses in call to print` ]

Ad

Answer

The story is a little more complicated on Windows than on Unix.

For Windows installations, when you install Python, the installer actually associates Python (.py) files with py.exe, an executable specifically made for launching Python on Windows. You can read all about it in PEP 397 -- Python launcher for Windows.

Since .py files are associated with that launcher, all the magic of reading the shebang line is implemented in py.exe. Long story short, your first line must read

#!/usr/bin/env python2

in order to work. In PEP 397, read the section titled "Python Script Launching" for more information.

Ad
source: stackoverflow.com
Ad