def _consume_multi_display_simple( progress_queue: 'Queue[ProgressTuple]', num_workers: int, num_simulations: int, max_width: int, fd: IO, ) -> None: start_date = datetime.now() isatty = fd.isatty() end = '\r' if isatty else '\n' try: completed: Set[Optional[int]] = set() _print_simple(len(completed), num_simulations, timedelta(), end, fd) last_print_date = start_date while len(completed) < num_simulations: progress: ProgressTuple = progress_queue.get() # type: ignore sim_index, now, t_stop, timescale = progress now_date = datetime.now() td = now_date - start_date td_print = now_date - last_print_date if now == t_stop: completed.add(sim_index) _print_simple(len(completed), num_simulations, td, end, fd) last_print_date = now_date elif isatty and td_print.total_seconds() >= 1: _print_simple(len(completed), num_simulations, td, end, fd) last_print_date = now_date finally: if isatty: print(file=fd)
def tty_sensitive_print(msg: str, file: typing.IO, **kwargs: Any) -> None: """ Strip ANSI escape sequences before printing, if `file` is not a TTY """ if not file.isatty() and not FORCE_COLOR: msg = ANSI_ESCAPE.sub("", msg) print(msg, file=file, **kwargs)
def __init__(self, screen: "BaseScreen", file: IO) -> None: if not file.isatty(): raise RuntimeError(f"Echo file={file!r} is not a terminal") self.__screen = screen self.__file = file self.__printed = False
def buffer_stdin(stdin: IO) -> Optional[IO]: if stdin.isatty(): return None temp_file = NamedTemporaryFile(delete=False) temp_file.write(sys.stdin.read().encode()) temp_file.flush() return temp_file
def _isatty(stream: IO) -> bool: """Returns ``True`` if the stream is part of a tty. Borrowed from ``click._compat``.""" # noinspection PyBroadException try: return stream.isatty() except Exception: return False
def display(grid: Dict[CoordT, str], cmap: CmapT, stdout: IO = None) -> None: if stdout is None: stdout = sys.stdout try: color = stdout.isatty() except AttributeError: color = False stdout.write(render(grid, cmap, color))
def isatty(fh: IO) -> bool: """Return True if fh has a controlling terminal. Notes: Use with e.g. :data:`sys.stdin`. """ try: return fh.isatty() except AttributeError: return False
def style_aware_write(fileobj: IO, msg: str) -> None: """ Write a string to a fileobject and strip its ANSI style sequences if required by allow_style setting :param fileobj: the file object being written to :param msg: the string being written """ if allow_style.lower() == STYLE_NEVER.lower() or \ (allow_style.lower() == STYLE_TERMINAL.lower() and not fileobj.isatty()): msg = strip_style(msg) fileobj.write(msg)
def ansi_aware_write(fileobj: IO, msg: str) -> None: """ Write a string to a fileobject and strip its ANSI escape sequences if required by allow_ansi setting :param fileobj: the file object being written to :param msg: the string being written """ if allow_ansi.lower() == ANSI_NEVER.lower() or \ (allow_ansi.lower() == ANSI_TERMINAL.lower() and not fileobj.isatty()): msg = strip_ansi(msg) fileobj.write(msg)
def _standalone_display_process( env: 'SimEnvironment', period_s: Union[int, float], fd: IO) -> Generator[simpy.Timeout, None, None]: interval = 1.0 end = '\r' if fd.isatty() else '\n' while True: sim_index, now, t_stop, timescale = env.get_progress() _print_progress(sim_index, now, t_stop, timescale, end=end, fd=fd) t0 = timeit.default_timer() yield env.timeout(interval) t1 = timeit.default_timer() interval *= period_s / (t1 - t0)
def generate(schema_file: TextIO, output_path: IO) -> None: interop_schema = avro.schema.parse(schema_file.read()) datum_writer = avro.io.DatumWriter() output = ((codec, gen_data(codec, datum_writer, interop_schema)) for codec in CODECS_TO_VALIDATE) if output_path.isatty(): json.dump({codec: base64.b64encode(data).decode() for codec, data in output}, output_path) return for codec, data in output: if codec == NULL_CODEC: output_path.write(data) continue base, ext = os.path.splitext(output_path.name) Path(f"{base}_{codec}{ext}").write_bytes(data)
def _print(self, stream: IO, message: str, **kwargs: Any) -> None: if None in (stream, message): return stream_tty = stream.isatty() print_tty = kwargs.pop('tty', True) if self._tty else kwargs.pop( 'tty', False) print_notty = kwargs.pop('notty', True) if self._notty else kwargs.pop( 'notty', False) if (stream_tty and print_tty) or (not stream_tty and print_notty): prefix = None if kwargs.pop('prefix', self._prefix): if callable(self._prefix): prefix = self._prefix() elif self._prefix: prefix = str(self._prefix) message = f'{prefix} {message}' if prefix else message if not stream.isatty() or not kwargs.pop('colors_enabled', self._colors_enabled): message = self.strip_style(message) else: style_args = { k: v for (k, v) in kwargs.items() if k in _style_keys } if len(style_args) > 0: message = self.style(message, **style_args) stream.write(message) endl = kwargs.pop('endl', self._endl) stream.write(endl) stream.flush()
def style(text: str, fg: Optional[int] = None, *, bold: bool = False, file: IO = sys.stdout) -> str: use_color = not os.environ.get("NO_COLOR") and file.isatty() if use_color: parts = [ fg and f"\033[{fg}m", bold and f"\033[{BOLD}m", text, f"\033[{RESET_ALL}m", ] return "".join([e for e in parts if e]) else: return text
def style( text: str, fg: typing.Optional[int] = None, *, bold: bool = False, file: typing.IO = sys.stdout, ) -> str: use_color = not os.environ.get("NO_COLOR") and file.isatty() if use_color: parts = [ fg and f"\033[{fg}m", bold and f"\033[{BOLD}m", text, f"\033[{RESET_ALL}m", ] return "".join([e for e in parts if e]) else: return text
def progress_bar(iterable: Iterable[T], file: IO = sys.stderr, **kwargs: Any) -> Iterable[T]: """ Return tqdm-wrapped iterable if output stream is a tty; else return iterable without tqdm. """ # Conditions: # file.isatty() - only show bar if this is an interactive terminal # len(iterable) > 1 - don't show progress bar when using -e on command-line. This # is a hack, so it will only show the progress bar if there is more than 1 rule to run. # not DEBUG - don't show progress bar with debug # not QUIET - don't show progress bar with quiet listified = list( iterable ) # Consume iterable once so we can check length and then use in tqdm. if file.isatty() and len(listified) > 1 and not DEBUG and not QUIET: # mypy doesn't seem to want to follow tqdm imports. Do this to placate. wrapped: Iterable[T] = tqdm(listified, file=file, **kwargs) return wrapped return listified
def pprintjson( *obj: Union[Dict, List], indent: int = 4, end: str = "\n", file: IO = None, flush: bool = False, ) -> None: """ :param *obj: Union[Dict, List]: :param indent: int: (Default value = 4) :param end: str: (Default value = "\n") :param file: IO: (Default value = None) :param flush: bool: (Default value = False) """ file = stdout if file is None else file json = [dumps(o, indent=indent) for o in obj] try: if file.isatty(): json = [highlight(j, JsonLexer(), TerminalFormatter()) for j in json] except AttributeError: pass print(*json, end=end, file=file, flush=flush)
def isatty(stream: t.IO) -> bool: try: return stream.isatty() except Exception: return False
def __init__(self, output: typing.IO): self._output = output self._use_color = output.isatty()
def isatty(ob: IO) -> bool: return hasattr(ob, "isatty") and ob.isatty()