"""
General helpers required for `tqdm.std`. """ import os import re import sys from functools import partial, partialmethod, wraps from inspect import signature # TODO consider using wcswidth third-party package for 0-width characters from unicodedata import east_asian_width from warnings import warn from weakref import proxy
_range, _unich, _unicode, _basestring = range, chr, str, str
CUR_OS = sys.platform
IS_WIN = any(CUR_OS.startswith(i) for i in ['win32', 'cygwin'])
IS_NIX = any(CUR_OS.startswith(i) for i in ['aix', 'linux', 'darwin', 'freebsd'])
RE_ANSI = re.compile(r"\x1b\[[;\d]*[A-Za-z]")
def envwrap(prefix, types=None, is_method=False): """
Override parameter defaults via `os.environ[prefix + param_name]`.
Maps UPPER_CASE env vars map to lower_case param names.
camelCase isn't supported (because Windows ignores case).
Precedence (highest first):
- call (`foo(a=3)`)
- environ (`FOO_A=2`)
- signature (`def foo(a=1)`)
Parameters
----------
prefix : str
Env var prefix, e.g. "FOO_"
types : dict, optional
Fallback mappings `{'param_name': type, ...}` if types cannot be
inferred from function signature.
Consider using `types=collections.defaultdict(lambda: ast.literal_eval)`.
is_method : bool, optional
Whether to use `functools.partialmethod`. If (default: False) use `functools.partial`.
$ FOO_A=42 FOO_C=1337 python -c 'import foo; foo.test(c=99)'
received: a=42, b=2, c=99
``` """ if types isNone:
types = {}
i = len(prefix)
env_overrides = {k[i:].lower(): v for k, v in os.environ.items() if k.startswith(prefix)}
part = partialmethod if is_method else partial
def wrap(func):
params = signature(func).parameters # ignore unknown env vars
overrides = {k: v for k, v in env_overrides.items() if k in params} # infer overrides' `type`s for k in overrides:
param = params[k] if param.annotation isnot param.empty: # typehints for typ in getattr(param.annotation, '__args__', (param.annotation,)): try:
overrides[k] = typ(overrides[k]) except Exception: pass else: break elif param.default isnotNone: # type of default value
overrides[k] = type(param.default)(overrides[k]) else: try: # `types` fallback
overrides[k] = types[k](overrides[k]) except KeyError: # keep unconverted (`str`) pass return part(func, **overrides) return wrap
def wrapper_getattr(self, name): """Actual `self.getattr` rather than self._wrapped.getattr""" try: return object.__getattr__(self, name) except AttributeError: # py2 return getattr(self, name)
def wrapper_setattr(self, name, value): """Actual `self.setattr` rather than self._wrapped.setattr""" return object.__setattr__(self, name, value)
def __init__(self, wrapped): """
Thin wrapper around a given object """
self.wrapper_setattr('_wrapped', wrapped)
class SimpleTextIOWrapper(ObjectWrapper): """
Change only `.write()` of the wrapped object by encoding the passed
value and passing the result to the wrapped object's `.write()` method. """ # pylint: disable=too-few-public-methods def __init__(self, wrapped, encoding):
super().__init__(wrapped)
self.wrapper_setattr('encoding', encoding)
def write(self, s): """
Encode `s` andpass to the wrapped object's `.write()` method. """ return self._wrapped.write(s.encode(self.wrapper_getattr('encoding')))
class DisableOnWriteError(ObjectWrapper): """
Disable the given `tqdm_instance` upon `write()` or `flush()` errors. """
@staticmethod def disable_on_exception(tqdm_instance, func): """
Quietly set `tqdm_instance.miniters=inf` if `func` raises `errno=5`. """
tqdm_instance = proxy(tqdm_instance)
h = windll.kernel32.GetStdHandle(io_handle)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi) if res:
(_bufx, _bufy, _curx, _cury, _wattr, left, top, right, bottom,
_maxx, _maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw) return right - left, bottom - top # +1 except Exception: # nosec pass returnNone, None
def _screen_shape_tput(*_): # pragma: no cover """cygwin xterm (windows)""" try: import shlex from subprocess import check_call # nosec return [int(check_call(shlex.split('tput ' + i))) - 1 for i in ('cols', 'lines')] except Exception: # nosec pass returnNone, None
def _screen_shape_linux(fp): # pragma: no cover
try: from array import array from fcntl import ioctl from termios import TIOCGWINSZ except ImportError: returnNone, None else: try:
rows, cols = array('h', ioctl(fp, TIOCGWINSZ, '\0' * 8))[:2] return cols, rows except Exception: try: return [int(os.environ[i]) - 1for i in ("COLUMNS", "LINES")] except (KeyError, ValueError): returnNone, None
def _environ_cols_wrapper(): # pragma: no cover """ Return a function which returns console width.
Supported: linux, osx, windows, cygwin. """
warn("Use `_screen_shape_wrapper()(file)[0]` instead of" " `_environ_cols_wrapper()(file)`", DeprecationWarning, stacklevel=2)
shape = _screen_shape_wrapper() ifnot shape: returnNone
@wraps(shape) def inner(fp): return shape(fp)[0]
return inner
def _term_move_up(): # pragma: no cover return''if (os.name == 'nt') and (colorama isNone) else'\x1b[A'
def _text_width(s): return sum(2if east_asian_width(ch) in'FW'else1for ch in str(s))
def disp_len(data): """
Returns the real on-screen length of a string which may contain
ANSI control codes and wide chars. """ return _text_width(RE_ANSI.sub('', data))
def disp_trim(data, length): """
Trim a string which may contain ANSI control characters. """ if len(data) == disp_len(data): return data[:length]
ansi_present = bool(RE_ANSI.search(data)) while disp_len(data) > length: # carefully delete one char at a time
data = data[:-1] if ansi_present and bool(RE_ANSI.search(data)): # assume ANSI reset is required return data if data.endswith("\033[0m") else data + "\033[0m" return data
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.