File: display.py

package info (click to toggle)
python-scrapy 2.13.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,664 kB
  • sloc: python: 52,028; xml: 199; makefile: 25; sh: 7
file content (51 lines) | stat: -rw-r--r-- 1,473 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
pprint and pformat wrappers with colorization support
"""

import ctypes
import platform
import sys
from pprint import pformat as pformat_
from typing import Any

from packaging.version import Version as parse_version


def _enable_windows_terminal_processing() -> bool:
    # https://stackoverflow.com/a/36760881
    kernel32 = ctypes.windll.kernel32  # type: ignore[attr-defined]
    return bool(kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7))


def _tty_supports_color() -> bool:
    if sys.platform != "win32":
        return True

    if parse_version(platform.version()) < parse_version("10.0.14393"):
        return True

    # Windows >= 10.0.14393 interprets ANSI escape sequences providing terminal
    # processing is enabled.
    return _enable_windows_terminal_processing()


def _colorize(text: str, colorize: bool = True) -> str:
    # pylint: disable=no-name-in-module
    if not colorize or not sys.stdout.isatty() or not _tty_supports_color():
        return text
    try:
        from pygments import highlight
    except ImportError:
        return text
    from pygments.formatters import TerminalFormatter
    from pygments.lexers import PythonLexer

    return highlight(text, PythonLexer(), TerminalFormatter())


def pformat(obj: Any, *args: Any, **kwargs: Any) -> str:
    return _colorize(pformat_(obj), kwargs.pop("colorize", True))


def pprint(obj: Any, *args: Any, **kwargs: Any) -> None:
    print(pformat(obj, *args, **kwargs))