Search code examples
pythonpython-3.xshebang

Using python interpreter explicitely does not ignore shebang


I have read Does shebang overwrite the python interpreter path, and it seems the given answer does not apply to me.

Some context: I am on Windows using C:\Program Files\Git\bin\bash.exe and having two python installations as you can see:

$ py --version
Python 3.10.11

$ which py
/c/Users/Username/AppData/Local/Programs/Python/Launcher/py

$ python3 --version
Python 3.9.10

$ which python3
/c/ProgramData/chocolatey/bin/python3

Have created a dummy python file shebang.py to print out the python version used

#!/usr/bin/env python3
import sys
print(sys. version)
$ py shebang.py 
3.9.10 (heads/mingw-v3.9.10-dirty:12d1cb5b7c, Dec  9 2022, 03:24:49)  [GCC UCRT 12.2.0 64 bit (AMD64)]

Looks like python3 is used and not py. Same behaviour if I call ./shebang.py .

How can I make sure py is used rather?

edit (@wRAR comment):

When I remove the shebang line from shebang.py I indeed can use py

$ py shebang.py 
3.10.11 (tags/v3.10.11:7d4cc5a, Apr  5 2023, 00:38:17) [MSC v.1929 64 bit (AMD64)]

Solution

  • You are using py. It's a Python interpreter selector, not Python 3.10. Shebang handling is most of py's job.

    If you want to override the shebang, py supports command-line flags to specify a Python version. For example,

    py -3.10 shebang.py
    

    will run shebang.py with Python 3.10, regardless of what any shebang line in the script might say.