scrapy / scrapy
1
"""
2
pprint and pformat wrappers with colorization support
3
"""
4

5 7
import ctypes
6 7
import platform
7 7
import sys
8 7
from distutils.version import LooseVersion as parse_version
9 7
from pprint import pformat as pformat_
10

11

12 7
def _enable_windows_terminal_processing():
13
    # https://stackoverflow.com/a/36760881
14 0
    kernel32 = ctypes.windll.kernel32
15 0
    return bool(kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7))
16

17

18 7
def _tty_supports_color():
19 7
    if sys.platform != "win32":
20 7
        return True
21

22 7
    if parse_version(platform.version()) < parse_version("10.0.14393"):
23 7
        return True
24

25
    # Windows >= 10.0.14393 interprets ANSI escape sequences providing terminal
26
    # processing is enabled.
27 7
    return _enable_windows_terminal_processing()
28

29

30 7
def _colorize(text, colorize=True):
31 7
    if not colorize or not sys.stdout.isatty() or not _tty_supports_color():
32 7
        return text
33 7
    try:
34 7
        from pygments import highlight
35 7
    except ImportError:
36 7
        return text
37
    else:
38 7
        from pygments.formatters import TerminalFormatter
39 7
        from pygments.lexers import PythonLexer
40 7
        return highlight(text, PythonLexer(), TerminalFormatter())
41

42

43 7
def pformat(obj, *args, **kwargs):
44 7
    return _colorize(pformat_(obj), kwargs.pop('colorize', True))
45

46

47 7
def pprint(obj, *args, **kwargs):
48 7
    print(pformat(obj, *args, **kwargs))

Read our documentation on viewing source code .

Loading