Skip to content

Commit a3d76a2

Browse files
committed
fix: distinguish stdout or stderr when colorizing output in argparse
Signed-off-by: Frost Ming <[email protected]>
1 parent bd2c7e8 commit a3d76a2

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

Lib/argparse.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -191,10 +191,10 @@ def __init__(
191191
self._whitespace_matcher = _re.compile(r'\s+', _re.ASCII)
192192
self._long_break_matcher = _re.compile(r'\n\n\n+')
193193

194-
def _set_color(self, color):
194+
def _set_color(self, color, *, file=None):
195195
from _colorize import can_colorize, decolor, get_theme
196196

197-
if color and can_colorize():
197+
if color and can_colorize(file=file):
198198
self._theme = get_theme(force_color=True).argparse
199199
self._decolor = decolor
200200
else:
@@ -2693,14 +2693,16 @@ def _check_value(self, action, value):
26932693
# Help-formatting methods
26942694
# =======================
26952695

2696-
def format_usage(self):
2697-
formatter = self._get_formatter()
2696+
def format_usage(self, formatter=None):
2697+
if formatter is None:
2698+
formatter = self._get_formatter()
26982699
formatter.add_usage(self.usage, self._actions,
26992700
self._mutually_exclusive_groups)
27002701
return formatter.format_help()
27012702

2702-
def format_help(self):
2703-
formatter = self._get_formatter()
2703+
def format_help(self, formatter=None):
2704+
if formatter is None:
2705+
formatter = self._get_formatter()
27042706

27052707
# usage
27062708
formatter.add_usage(self.usage, self._actions,
@@ -2734,12 +2736,16 @@ def _get_formatter(self):
27342736
def print_usage(self, file=None):
27352737
if file is None:
27362738
file = _sys.stdout
2737-
self._print_message(self.format_usage(), file)
2739+
formatter = self._get_formatter()
2740+
formatter._set_color(self.color, file=file)
2741+
self._print_message(self.format_usage(formatter=formatter), file)
27382742

27392743
def print_help(self, file=None):
27402744
if file is None:
27412745
file = _sys.stdout
2742-
self._print_message(self.format_help(), file)
2746+
formatter = self._get_formatter()
2747+
formatter._set_color(self.color, file=file)
2748+
self._print_message(self.format_help(formatter=formatter), file)
27432749

27442750
def _print_message(self, message, file=None):
27452751
if message:

0 commit comments

Comments
 (0)