Skip to content

poetry env use X.Y fails on Windows #2117

@absassi

Description

@absassi
  • I am on the latest Poetry version.

  • I have searched the issues of this repo and believe that this is not a duplicate.

  • If an exception occurs when executing a command, I executed it again in debug mode (-vvv option).

  • OS version and name: Windows 10

  • Poetry version: 1.0.5

  • Link of a Gist with the contents of your pyproject.toml file: not needed

Issue

The shortcut command poetry env use X.Y to select the environment for Python X.Y, as documented in Managing environments, is broken in Windows. One is required instead to find, copy and paste the full path to Python executable.

Note that the documentation even says "especially Windows where pyenv is not available".

>poetry env use 3.7
'python3.7' is not recognized as an internal or external command,
operable program or batch file.

The reason is quite simple: CPython installation in Windows doesn't provide pythonX.Y.exe, so even if you have all of them in PATH, Poetry can only find the first one. They do, however, provide registry keys with installation locations, which Poetry can use to resolve X.Y to the Python interpreter path.

This piece of code should find the path to Python, given the version number as a X.Y string:

import os
try:
    import winreg
except ImportError:
    import _winreg as winreg

def find_python_interpreter(version):
    for hkey, prefix in (
        (winreg.HKEY_CURRENT_USER, "Software"),
        (winreg.HKEY_CURRENT_USER, "Software\\WOW6432Node"),
        (winreg.HKEY_LOCAL_MACHINE, "Software"),
        (winreg.HKEY_LOCAL_MACHINE, "Software\\WOW6432Node"),
    ):
        try:
            value = winreg.QueryValue(hkey, "{}\\Python\\PythonCore\\{}\\InstallPath".format(prefix, version))
        except FileNotFoundError:
            continue
        python = os.path.join(value, "python.exe")
        if os.path.exists(python):
            return python
    return None

I have adjusted the code above to make it compatible with Python 2, but I have not tested afterwards, so please forgive any mistakes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/venvRelated to virtualenv managementkind/bugSomething isn't working as expected

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions