Using Python Launcher and Shebang to Manage Multiple Python Versions on Windows and Linux
This article explains how Python's launcher and shebang lines can be used on Windows and Linux to select specific Python interpreter versions, covering installation, configuration, and command‑line examples for running scripts with Python 2.x or 3.x.
The author introduces the common problem of needing different Python interpreter versions (Python 2.x vs Python 3.x) for different scripts and the confusion caused by the default python command that follows the system PATH.
On Unix‑like systems the solution is to use a shebang line (e.g., #!/usr/bin/python2) combined with a symbolic link that points the generic python command to the desired interpreter.
On Windows, PEP 397 introduced the Python Launcher (executables py.exe and pyw.exe) which reads the shebang in a script and automatically selects the appropriate interpreter.
Installation of the launcher is optional during the Python installer setup (starting with Python 3.3) or can be performed separately; once installed it resides in the system PATH.
The launcher provides two executables: py.exe for console programs and pyw.exe for GUI programs. Their locations can be verified with:
where py
C:\Windows\py.exe
where pyw.exe
C:\Windows\pyw.exeTypical usage examples:
#! python2.7
import sys
print(sys.version)
# Execution
M:\>py test.py # runs with Python 2.7Changing the shebang to #! python3 makes the same script run with the latest Python 3 interpreter:
#! python3
import sys
print(sys.version)
M:\>py test.py # runs with Python 3.7If a script lacks a shebang, the launcher defaults to the newest installed interpreter:
import sys
print(sys.version)
M:\>py test.py # runs with Python 3.7Explicit version selection is also possible via command‑line switches, e.g.:
M:\>py -3 test.py # force Python 3
M:\>py -3.5 test.py # force Python 3.5In summary, the Python Launcher simplifies version management on Windows, while shebang lines provide a portable way to specify interpreter versions on both Windows and Linux, eliminating the need for manual PATH adjustments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
