mirror of
https://github.com/StevenBlack/hosts.git
synced 2025-03-14 10:36:53 +00:00
Check if terminal supports color
Closes gh-151.
This commit is contained in:
@ -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
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user