diff options
author | Giampaolo Rodola <g.rodola@gmail.com> | 2020-02-15 06:44:23 -0800 |
---|---|---|
committer | Giampaolo Rodola <g.rodola@gmail.com> | 2020-02-15 06:44:23 -0800 |
commit | 5c356beeb0de56f6d7badc24df8890f7199bf04b (patch) | |
tree | 191e38b431605c0d2ea42c1d9712f3bd778b6d64 | |
parent | 5053f08c7ec02f31d424b9dc2f59788ee4e2cf49 (diff) | |
download | psutil-5c356beeb0de56f6d7badc24df8890f7199bf04b.tar.gz |
refactoring
-rw-r--r-- | psutil/_common.py | 32 |
1 files changed, 16 insertions, 16 deletions
diff --git a/psutil/_common.py b/psutil/_common.py index 5b2d4214..693516f6 100644 --- a/psutil/_common.py +++ b/psutil/_common.py @@ -9,9 +9,7 @@ from __future__ import division, print_function -import atexit import contextlib -import ctypes import errno import functools import os @@ -762,7 +760,7 @@ else: @memoize def term_supports_colors(file=sys.stdout): if os.name == 'nt': - return True # implemented via ctypes + return True try: import curses assert file.isatty() @@ -792,16 +790,19 @@ def hilite(s, color="green", bold=False): def print_color(s, color="green", bold=False, file=sys.stdout): - def _stderr_handle(): + """Print a colorized version of string.""" + if not term_supports_colors(): + print(s, file=file) + elif POSIX: + print(hilite(s, color, bold), file=file) + else: + import ctypes + # Windows + DEFAULT_COLOR = 7 GetStdHandle = ctypes.windll.Kernel32.GetStdHandle - STD_ERROR_HANDLE_ID = ctypes.c_ulong(0xfffffff4) - GetStdHandle.restype = ctypes.c_ulong - handle = GetStdHandle(STD_ERROR_HANDLE_ID) - atexit.register(ctypes.windll.Kernel32.CloseHandle, handle) - return handle + SetConsoleTextAttribute = \ + ctypes.windll.Kernel32.SetConsoleTextAttribute - def win_colorprint(s, color, bold=False): - DEFAULT_COLOR = 7 colors = dict(green=2, red=4, brown=6) try: color = colors[color] @@ -810,17 +811,16 @@ def print_color(s, color="green", bold=False, file=sys.stdout): color, list(colors.keys()))) if bold and color <= 7: color += 8 - handle = _stderr_handle() - SetConsoleTextAttribute = \ - ctypes.windll.Kernel32.SetConsoleTextAttribute + + STD_ERROR_HANDLE_ID = ctypes.c_ulong(0xfffffff4) + GetStdHandle.restype = ctypes.c_ulong + handle = GetStdHandle(STD_ERROR_HANDLE_ID) SetConsoleTextAttribute(handle, color) try: print(s) finally: SetConsoleTextAttribute(handle, DEFAULT_COLOR) - win_colorprint(s, color, bold) - if bool(os.getenv('PSUTIL_DEBUG', 0)): import inspect |