Skip to content

Commit 3776ec8

Browse files
committed
Got color code support working in Windows.
I tested this on Windows 10 in VirtualBox. Based on the docs, this should work in all Windows versions >= 10, so I coded it as such. If you're on an older Windows, this will simply not emit colors.
1 parent 77ee98d commit 3776ec8

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

linodecli/response.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,33 @@
44
"""
55
from __future__ import print_function
66

7+
import os
8+
import platform
9+
10+
DO_COLORS = True
11+
# !! Windows compatibility for ANSI color codes !!
12+
#
13+
# If we're running on windows, we need to run the "color" command to enable
14+
# ANSI color code support.
15+
if platform.system() == "Windows":
16+
ver = platform.version()
17+
18+
if '.' in ver:
19+
ver = ver.split('.', 1)[0]
20+
21+
try:
22+
verNum = int(ver)
23+
except ValueError:
24+
DO_COLORS = False
25+
26+
# windows 10+ supports ANSI color codes after running the 'color' command to
27+
# properly set up the command prompt. Older versions of windows do not, and
28+
# we should not attempt to use them there.
29+
if verNum >= 10:
30+
os.system("color")
31+
else:
32+
DO_COLORS = False
33+
734

835
CLEAR_COLOR = "\x1b[0m"
936
COLOR_CODE_MAP = {
@@ -16,6 +43,14 @@
1643

1744

1845
def colorize_string(string, color):
46+
"""
47+
Returns the requested string, wrapped in ANSI color codes to colorize it as
48+
requested. On platforms where colors are not supported, this just returns
49+
the string passed into it.
50+
"""
51+
if not DO_COLORS:
52+
return string
53+
1954
col = COLOR_CODE_MAP.get(color, CLEAR_COLOR)
2055

2156
return "{}{}{}".format(

0 commit comments

Comments
 (0)