From: gfyoung Date: Wed, 24 May 2017 22:03:07 +0000 (-0400) Subject: Check if terminal supports color X-Git-Url: http://git.99rst.org/?a=commitdiff_plain;h=2d6a8676a4b7849bece8a035ba44bb67afad0147;p=stevenblack-hosts.git Check if terminal supports color Closes gh-151. --- diff --git a/updateHostsFile.py b/updateHostsFile.py index 3b0bff825..8715019e3 100644 --- a/updateHostsFile.py +++ b/updateHostsFile.py @@ -971,6 +971,28 @@ class Colors(object): ENDC = "\033[0m" +def supports_color(): + """ + Check whether the running terminal or command prompt supports color. + + Inspired by StackOverflow link (and Django implementation) here: + + https://stackoverflow.com/questions/7445658 + + Returns + ------- + colors_supported : bool + Whether the running terminal or command prompt supports color. + """ + + sys_platform = sys.platform + supported = sys_platform != "Pocket PC" and (sys_platform != "win32" + or "ANSICON" in os.environ) + + atty_connected = hasattr(sys.stdout, "isatty") and sys.stdout.isatty() + return supported and atty_connected + + def colorize(text, color): """ Wrap a string so that it displays in a particular color. @@ -978,6 +1000,9 @@ def colorize(text, color): This function adds a prefix and suffix to a text string so that it is displayed as a particular color, either in command prompt or the terminal. + If the running terminal or command prompt does not support color, the + original text is returned without being wrapped. + Parameters ---------- text : str @@ -988,9 +1013,12 @@ def colorize(text, color): Returns ------- wrapped_str : str - The wrapped string to display in color. + The wrapped string to display in color, if possible. """ + if not supports_color(): + return text + return color + text + Colors.ENDC