From 1a3a4987afe8612d9a5180e1e069ffbbab367db1 Mon Sep 17 00:00:00 2001 From: Joel Holdsworth Date: Mon, 30 Sep 2019 18:35:19 +0100 Subject: [PATCH] Added FORCE_COLOR and NO_COLOR environment variables --- README.rst | 8 ++++++-- colorama/ansitowin32.py | 11 +++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/README.rst b/README.rst index 20c73fa..f81a29b 100644 --- a/README.rst +++ b/README.rst @@ -174,12 +174,16 @@ init(autoreset=False): init(strip=None): Pass ``True`` or ``False`` to override whether ansi codes should be stripped from the output. The default behaviour is to strip if on Windows - or if output is redirected (not a tty). + or if output is redirected (not a tty), and if the ``FORCE_COLOR`` + environment variable is not set to ``1``, ``y`` or ``Y`` or ``NO_COLOR`` is + set to ``1``, ``y`` or ``Y``. init(convert=None): Pass ``True`` or ``False`` to override whether to convert ANSI codes in the output into win32 calls. The default behaviour is to convert if on Windows - and output is to a tty (terminal). + and output is to a tty (terminal), or the ``FORCE_COLOR`` environment + variable is set to ``1``, ``y`` or ``Y`` and ``NO_COLOR`` is not set to + ``1``, ``y`` or ``Y``. init(wrap=True): On Windows, colorama works by replacing ``sys.stdout`` and ``sys.stderr`` diff --git a/colorama/ansitowin32.py b/colorama/ansitowin32.py index 359c92b..1d45386 100644 --- a/colorama/ansitowin32.py +++ b/colorama/ansitowin32.py @@ -87,14 +87,21 @@ def __init__(self, wrapped, convert=None, strip=None, autoreset=False): # to support the ANSI codes. conversion_supported = on_windows and winapi_test() + # check if this is a TTY or if the FORCE_COLOR environment variable + # has been set and NO_COLOR has not been set. + isatty = not self.stream.closed and self.stream.isatty() + force_color = os.environ.get('FORCE_COLOR', None) in ('1', 'y', 'Y') + no_color = os.environ.get('NO_COLOR', None) in ('1', 'y', 'Y') + color_allowed = (isatty or force_color) and not no_color + # should we strip ANSI sequences from our output? if strip is None: - strip = conversion_supported or (not self.stream.closed and not self.stream.isatty()) + strip = conversion_supported or (not self.stream.closed and not color_allowed) self.strip = strip # should we should convert ANSI sequences into win32 calls? if convert is None: - convert = conversion_supported and not self.stream.closed and self.stream.isatty() + convert = conversion_supported and (not self.stream.closed and color_allowed) self.convert = convert # dict of ansi codes to win32 functions and parameters