Skip to content

click.getchar does not return Unicode on Windows #537

@intrinseca

Description

@intrinseca

Test Script (Python 3.4.3 on Windows 7 x64):

import click
print(click.getchar()) # press 'a' key, prints "b'a'" i.e. a byte string

When calling click.getchar() on Windows mscvrt.getch is used in _termui_impl.getchar rather than mscvrt.getwch.

This means you get a byte string back, which defeats the Ctrl-C/Ctrl-D processing in _translate_ch_to_exc and breaks comparisons with the return value. The documentation for msvcrt advises that the wide char functions should be used wherever possible.

I've patched this over by changing getchar to the following (also with a tweak to use the built in echoing rather than putchar, which is a typo for putch anyway):

def getchar(echo):
    if echo:
        rv = msvcrt.getwche()
    else:
        rv = msvcrt.getwch()

    _translate_ch_to_exc(rv)
    if PY2:
        enc = getattr(sys.stdin, 'encoding', None)
        if enc is not None:
            rv = rv.decode(enc, 'replace')
        else:
            rv = rv.decode('cp1252', 'replace')
    return rv

But I don't really want to embark on rigorously testing this (e.g. on Python 2), given the complexity of all the encoding handling. I'm not sure how you would even write a test for this, since it's so tied to the console I/O?

(if click uses the wide char API, then does it even need the PY2 branch?)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugwindowsIssues pertaining to the Windows environment

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions