Skip to content

Commit 607106c

Browse files
committed
Strip color codes when redirecting w/ ppaged()
1 parent eaf2918 commit 607106c

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

cmd2/cmd2.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,9 @@ def ppaged(self, msg: str, end: str='\n', chop: bool=False) -> None:
703703
else:
704704
break
705705
self.pipe_proc = None
706+
elif self.redirecting and self.colors.lower() in (constants.COLORS_NEVER.lower(),
707+
constants.COLORS_TERMINAL.lower()):
708+
self.decolorized_write(self.stdout, msg_str)
706709
else:
707710
self.stdout.write(msg_str)
708711
except BrokenPipeError:

tests/test_cmd2.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2109,6 +2109,24 @@ def test_ppaged(base_app):
21092109
out = base_app.stdout.getvalue()
21102110
assert out == msg + end
21112111

2112+
def test_ppaged_strips_color_when_redirecting(base_app):
2113+
msg = 'testing...'
2114+
end = '\n'
2115+
base_app.colors = cmd2.constants.COLORS_TERMINAL
2116+
base_app.redirecting = True
2117+
base_app.ppaged(Fore.RED + msg)
2118+
out = base_app.stdout.getvalue()
2119+
assert out == msg + end
2120+
2121+
def test_ppaged_strips_color_when_redirecting_if_always(base_app):
2122+
msg = 'testing...'
2123+
end = '\n'
2124+
base_app.colors = cmd2.constants.COLORS_ALWAYS
2125+
base_app.redirecting = True
2126+
base_app.ppaged(Fore.RED + msg)
2127+
out = base_app.stdout.getvalue()
2128+
assert out == Fore.RED + msg + end
2129+
21122130
# we override cmd.parseline() so we always get consistent
21132131
# command parsing by parent methods we don't override
21142132
# don't need to test all the parsing logic here, because

0 commit comments

Comments
 (0)