How to have python 2 and 3 both on windows?

Eryk Sun eryksun at gmail.com
Sun Apr 24 10:18:27 EDT 2022


On 4/23/22, Sunil KR via Python-list <python-list at python.org> wrote:
>
> I am happy with how the python starts up. When I use python I get
> python 2. I am ok with using py -3 for my new scripts, even using the
> shebang like #!py -3

`#!py -3` is not a valid shebang for the py launcher. Use `#!python3`
to run a script with the highest version of Python 3 that's registered
on your system. Or for cross-platform support, use
`#!/usr/bin/python3`.

> I don't want to put a unix (or for that matter windows) path in the shebang,
> as it is not platform portable

The launcher supports builtin virtual shebangs, including:

* #!python[X[.Y][-32|-64]]
* #!/usr/bin/python[X[.Y][-32|-64]]
* #!/usr/bin/env python[X[.Y][-32|-64]]
* #!/usr/local/bin/python[X[.Y][-32|-64]]

The implementation of the `/usr/bin/env` virtual shebang searches PATH
for a given command that's exactly "python" (no version spec) or any
command that doesn't start with "python". If a "python" command has a
version spec, then PATH is not searched, and it works the same as a
`#!pythonX[.Y]` shebang. The latter is because a normal Python
installation doesn't include versioned executable names, so the
launcher doesn't even try to search PATH for something like
"python3.11.exe".

You can set the default version to use via the PY_PYTHON environment
variable, e.g. `set PY_PYTHON=3.9`. If Python 3 is requested without a
specific version (e.g. via `py -3` at the command line, or the shebang
`#!python3`), then the default 3.x version to run can be set via the
PY_PYTHON3 environment variable, e.g. `set PY_PYTHON3=3.10`. The
default for Python 2 is set similarly via PY_PYTHON2.

The launcher also supports real file paths in shebangs. Generally
you'd only use a real path in order to run in a virtual environment,
such as #!"C:\Path\to\venv\Scripts\python.exe".


More information about the Python-list mailing list