Check if terminal supports color
authorgfyoung <redacted>
Wed, 24 May 2017 22:03:07 +0000 (18:03 -0400)
committergfyoung <redacted>
Sun, 28 May 2017 16:40:32 +0000 (12:40 -0400)
Closes gh-151.

updateHostsFile.py

index 3b0bff8252dcc5340002ddd0baf5320d349845a2..8715019e331855819475c1ef8d7e71e36d404c56 100644 (file)
@@ -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
 
 
git clone https://git.99rst.org/PROJECT