Skip to content
Myr

Merge pull request #451 from mitsuhiko/feature/unicode-cmd

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Added support for dealing with unicode argv on win py2

authored by Armin Ronacher · committed by Armin Ronacher · parents 7951a73, 8e768e7 · Browse files · 6 files+332 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+332 added−2 removed

  • other:+332 added−2 removed

6 files+332 added−2 removed

modified:click/_compat.py+37 added
165 unmodified lines
166 pass167 else:168 msvcrt.setmode(fileno, os.O_BINARY)169 return f170171 class WindowsConsole(_FixupStream):172 def __repr__(self):173 return '<%s name=%r>' % (174 self.__class__.__name__,175 self.name,176 )177178 from ._winconsole import _get_windows_console_stream179 else:180 set_binary_mode = lambda x: x181 _get_windows_console_stream = lambda *x: None182183 def isidentifier(x):184 return _identifier_re.search(x) is not None185
6 unmodified lines
192 def get_binary_stderr():193 return set_binary_mode(sys.stderr)194195 def get_text_stdin(encoding=None, errors=None):196 rv = _get_windows_console_stream(sys.stdin, encoding, errors)197 if rv is not None:198 return rv199 return _make_text_stream(sys.stdin, encoding, errors)200201 def get_text_stdout(encoding=None, errors=None):202 rv = _get_windows_console_stream(sys.stdout, encoding, errors)203 if rv is not None:204 return rv205 return _make_text_stream(sys.stdout, encoding, errors)206207 def get_text_stderr(encoding=None, errors=None):208 rv = _get_windows_console_stream(sys.stderr, encoding, errors)209 if rv is not None:210 return rv211 return _make_text_stream(sys.stderr, encoding, errors)212213 def filename_to_ui(value):214 if isinstance(value, bytes):
299 unmodified lines
514if WIN:515 # Windows has a smaller terminal516 DEFAULT_COLUMNS = 79517518 def _get_argv_encoding():519 import locale520 return locale.getpreferredencoding()521522 if PY2:523 def raw_input(prompt=''):524 sys.stderr.flush()525 if prompt:526 stdout = _default_text_stdout()527 stdout.write(prompt)528 stdin = _default_text_stdin()529 return stdin.readline().rstrip('\r\n')530531 try:532 import colorama533 except ImportError:534 pass
34 unmodified lines
569 def get_winterm_size():570 win = colorama.win32.GetConsoleScreenBufferInfo(571 colorama.win32.STDOUT).srWindow572 return win.Right - win.Left, win.Bottom - win.Top573else:574 def _get_argv_encoding():575 return getattr(sys.stdin, 'encoding', None) or get_filesystem_encoding()576577578def term_len(x):579 return len(strip_ansi(x))
31 unmodified lines
611 return rv612 return func613614615_default_text_stdin = _make_cached_stream_func(616 lambda: sys.stdin, get_text_stdin)617_default_text_stdout = _make_cached_stream_func(618 lambda: sys.stdout, get_text_stdout)619_default_text_stderr = _make_cached_stream_func(620 lambda: sys.stderr, get_text_stderr)
13 unmodified lines
added:click/_winconsole.py+248 added
1# -*- coding: utf-8 -*-2# This module is based on the excellent work by Adam Bartoš who3# provided a lot of what went into the implementation here in4# the discussion to issue1602 in the Python bug tracker.5#6# There are some general differences in regards to how this works7# compared to the original patches as we do not need to patch8# the entire interpreter but just work in our little world of9# echo and prmopt.1011import io12import sys13import ctypes14from click._compat import _NonClosingTextIOWrapper, text_type15from ctypes import byref, POINTER, pythonapi, c_int, c_char, c_char_p, \16 c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE17from ctypes.wintypes import LPWSTR, LPCWSTR181920PY2 = sys.version_info[0] == 22122c_ssize_p = POINTER(c_ssize_t)2324PyObject_GetBuffer = pythonapi.PyObject_GetBuffer25PyBuffer_Release = pythonapi.PyBuffer_Release2627kernel32 = windll.kernel3228GetStdHandle = kernel32.GetStdHandle29ReadConsoleW = kernel32.ReadConsoleW30WriteConsoleW = kernel32.WriteConsoleW31GetLastError = kernel32.GetLastError32GetCommandLineW = WINFUNCTYPE(LPWSTR)(33 ('GetCommandLineW', windll.kernel32))34CommandLineToArgvW = WINFUNCTYPE(35 POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(36 ('CommandLineToArgvW', windll.shell32))373839STDIN_HANDLE = GetStdHandle(-10)40STDOUT_HANDLE = GetStdHandle(-11)41STDERR_HANDLE = GetStdHandle(-12)424344PyBUF_SIMPLE = 045PyBUF_WRITABLE = 14647ERROR_SUCCESS = 048ERROR_NOT_ENOUGH_MEMORY = 849ERROR_OPERATION_ABORTED = 9955051STDIN_FILENO = 052STDOUT_FILENO = 153STDERR_FILENO = 25455EOF = b'\x1a'56MAX_BYTES_WRITTEN = 32767575859class Py_buffer(ctypes.Structure):60 _fields_ = [61 ('buf', c_void_p),62 ('obj', py_object),63 ('len', c_ssize_t),64 ('itemsize', c_ssize_t),65 ('readonly', c_int),66 ('ndim', c_int),67 ('format', c_char_p),68 ('shape', c_ssize_p),69 ('strides', c_ssize_p),70 ('suboffsets', c_ssize_p),71 ('internal', c_void_p)72 ]7374 if PY2:75 _fields_.insert(-1, ('smalltable', c_ssize_t * 2))767778def get_buffer(obj, writable=False):79 buf = Py_buffer()80 flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE81 PyObject_GetBuffer(py_object(obj), byref(buf), flags)82 try:83 buffer_type = c_char * buf.len84 return buffer_type.from_address(buf.buf)85 finally:86 PyBuffer_Release(byref(buf))878889class _WindowsConsoleRawIOBase(io.RawIOBase):9091 def __init__(self, handle):92 self.handle = handle9394 def isatty(self):95 super(WindowsConsoleRawIOBase, self).isatty()96 return True979899class _WindowsConsoleReader(_WindowsConsoleRawIOBase):100101 def readable(self):102 return True103104 def readinto(self, b):105 bytes_to_be_read = len(b)106 if not bytes_to_be_read:107 return 0108 elif bytes_to_be_read % 2:109 raise ValueError('cannot read odd number of bytes from '110 'UTF-16-LE encoded console')111112 buffer = get_buffer(b, writable=True)113 code_units_to_be_read = bytes_to_be_read // 2114 code_units_read = c_ulong()115116 rv = ReadConsoleW(self.handle, buffer, code_units_to_be_read,117 byref(code_units_read), None)118 if GetLastError() == ERROR_OPERATION_ABORTED:119 # wait for KeyboardInterrupt120 time.sleep(0.1)121 if not rv:122 raise OSError('Windows error: %s' % GetLastError())123124 if buffer[0] == EOF:125 return 0126 return 2 * code_units_read.value127128129class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):130131 def writable(self):132 return True133134 @staticmethod135 def _get_error_message(errno):136 if errno == ERROR_SUCCESS:137 return 'ERROR_SUCCESS'138 elif errno == ERROR_NOT_ENOUGH_MEMORY:139 return 'ERROR_NOT_ENOUGH_MEMORY'140 return 'Windows error %s' % errno141142 def write(self, b):143 bytes_to_be_written = len(b)144 buf = get_buffer(b)145 code_units_to_be_written = min(bytes_to_be_written,146 MAX_BYTES_WRITTEN) // 2147 code_units_written = c_ulong()148149 WriteConsoleW(self.handle, buf, code_units_to_be_written,150 byref(code_units_written), None)151 bytes_written = 2 * code_units_written.value152153 if bytes_written == 0 and bytes_to_be_written > 0:154 raise OSError(self._get_error_message(GetLastError()))155 return bytes_written156157158class ConsoleStream(object):159160 def __init__(self, text_stream, byte_stream):161 self._text_stream = text_stream162 self.buffer = byte_stream163164 @property165 def name(self):166 return self.buffer.name167168 def write(self, x):169 if isinstance(x, text_type):170 return self._text_stream.write(x)171 try:172 self.flush()173 except Exception:174 pass175 return self.buffer.write(x)176177 def writelines(self, lines):178 for line in lines:179 self.write(line)180181 def __getattr__(self, name):182 return getattr(self._text_stream, name)183184 def isatty(self):185 return self.buffer.isatty()186187 def __repr__(self):188 return '<ConsoleStream name=%r encoding=%r>' % (189 self.name,190 self.encoding,191 )192193194def _get_text_stdin():195 text_stream = _NonClosingTextIOWrapper(196 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),197 'utf-16-le', 'strict', line_buffering=True)198 return ConsoleStream(text_stream, sys.stdin)199200201def _get_text_stdout():202 text_stream = _NonClosingTextIOWrapper(203 _WindowsConsoleWriter(STDOUT_HANDLE),204 'utf-16-le', 'strict', line_buffering=True)205 return ConsoleStream(text_stream, sys.stdout)206207208def _get_text_stderr():209 text_stream = _NonClosingTextIOWrapper(210 _WindowsConsoleWriter(STDERR_HANDLE),211 'utf-16-le', 'strict', line_buffering=True)212 return ConsoleStream(text_stream, sys.stderr)213214215def _get_windows_argv():216 argc = c_int(0)217 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))218 argv = [argv_unicode[i] for i in range(0, argc.value)]219220 if not hasattr(sys, 'frozen'):221 argv = argv[1:]222 while len(argv) > 0:223 arg = argv[0]224 if not arg.startswith('-') or arg == '-':225 break226 argv = argv[1:]227 if arg == '-m':228 break229 if arg == '-c':230 argv[0] = '-c'231 break232233 return argv234235236_stream_factories = {237 0: _get_text_stdin,238 1: _get_text_stdout,239 2: _get_text_stderr,240}241242243def _get_windows_console_stream(f, encoding, errors):244 if encoding in ('utf-16-le', None) \245 and errors in ('strict', None):246 func = _stream_factories.get(f.fileno())247 if func is not None:248 return func()
modified:click/core.py+3 added-1 removed
668 unmodified lines
669 else:670 _check_for_unicode_literals()671672 if args is None:673 args = sys.argv[1:]673 args = get_os_args()674 else:675 args = list(args)676677 if prog_name is None:678 prog_name = make_str(os.path.basename(679 sys.argv and sys.argv[0] or __file__))680
1030 unmodified lines
171117121713# Circular dependency between decorators and core1714from .decorators import command, group1715from .utils import get_os_args
modified:click/types.py+14 added-1 removed
352 unmodified lines
353 :param readable: if true, a readable check is performed.354 :param resolve_path: if this is true, then the path is fully resolved355 before the value is passed onwards. This means356 that it's absolute and symlinks are resolved.357 :param type: optionally a string type that should be used to358 represent the path. The default is `None` which359 means the return value will be either bytes or360 unicode depending on what makes most sense given the361 input data Click deals with.362 """363 envvar_list_splitter = os.path.pathsep364365 def __init__(self, exists=False, file_okay=True, dir_okay=True,361 writable=False, readable=True, resolve_path=False):366 writable=False, readable=True, resolve_path=False,367 path_type=None):368 self.exists = exists369 self.file_okay = file_okay370 self.dir_okay = dir_okay371 self.writable = writable372 self.readable = readable373 self.resolve_path = resolve_path374 self.type = path_type375376 if self.file_okay and not self.dir_okay:377 self.name = 'file'378 self.path_type = 'File'
39 unmodified lines
418 self.path_type,419 filename_to_ui(value)420 ), param, ctx)421422 if self.type is not None and not isinstance(rv, self.type):423 if self.type is text_type:424 rv = rv.decode(get_filesystem_encoding())425 else:426 rv = rv.encode(get_filesystem_encoding())427428 return rv429430431class Tuple(CompositeParamType):
105 unmodified lines
modified:click/utils.py+19 added
9 unmodified lines
10 _default_text_stdout, _default_text_stderr, is_bytes, WIN1112if not PY2:13 from ._compat import _find_binary_writer14 if WIN:15 from ._winconsole import _get_windows_argv161718echo_native_types = string_types + (bytes, bytearray)19
362 unmodified lines
382 f = KeepOpenFile(f)383 return f384385386def get_os_args():387 """This returns the argument part of sys.argv in the most appropriate388 form for processing. What this means is that this return value is in389 a format that works for Click to process but does not necessarily390 correspond well to what's actually standard for the interpreter.391392 On most environments the return value is ``sys.argv[:1]`` unchanged.393 However if you are on Windows and running Python 2 the return value394 will actually be a list of unicode strings instead because the395 default behavior on that platform otherwise will not be able to396 carry all possible values that sys.argv can have.397 """398 if not PY2 or os.name != 'nt':399 return sys.argv[1:]400 return _get_windows_argv()401402403def format_filename(filename, shorten=False):404 """Formats a filename for user display. The main purpose of this405 function is to ensure that the filename can be displayed at all. This406 will decode the filename to unicode if necessary in a way that it will
62 unmodified lines
modified:CHANGES+11 added
20 unmodified lines
21 available.22- Click used to return byte strings on Python 2 in some unit-testing23 situations. This has been fixed to correctly return unicode strings24 now.25- For Windows users on Python 2, Click will now handle Unicode more26 correctly handle Unicode coming in from the system. This also has27 the disappointing side effect that filenames will now be always28 unicode by default in the `Path` type which means that this can29 introduce small bugs for code not aware of this.30- Added a `type` parameter to `Path` to force a specific string type31 on the value.32- For users running Python 2 the echo() and prompt() functions now work33 with unicode in the Python windows console. For Python 3 the work34 is delegated to the Python interpreter as general support for Unicode35 in the console is implemented to some degree.3637Version 5.138-----------39
251 unmodified lines