Skip to content

Better handling of the msvcrt.getch() problem in Windows+Python3 : Generic solution. #2

Description

@malversan

As you already know (commit 79bfdd6), in Python 3 the msvcrt.getch() call returns bytes instead of chars. You patched it by providing different versions of the PlatformWindows.getchars() method depending on the Python version.

I found a much better solution that doesn´t depend on the Python version or the OS being used, that consists in allowing any platform to produce either chars or bytes, and then manage the result correctly. This prevents the bug ever reappearing if there is some similar platform change in the future, by supporting both possibilities.

So you can leave the PlatformWindows.getchars() method as it was:

    def getchars(self, blocking=True):
        """Get characters on Windows."""
        if blocking:
            yield self.msvcrt.getch()
        while self.msvcrt.kbhit():
            yield self.msvcrt.getch()

and then manage the result in the more generic Platform.getkey() method.
Instead of:

            buffer += c

it should do:

            try:
                buffer += c
            except TypeError:
                buffer += ''.join([chr(b) for b in c]])

This supports any platform that captures chars, multichars, bytes or multibytes. And also complies with the Python philosophy of trying instead of checking.

Tested in:
Windows 8.1, Python 3.6.1
Ubuntu 16.04, Python 3.5.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions