GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — gh-139946: distinguish stdout or stderr when colorizing output in argparse by frostming · Pull Request #140495 · python/cpython

gh-139946: distinguish stdout or stderr when colorizing output in argparse #140495

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
savannahostrowski merged 6 commits into python:main from frostming:fix/colorize-argparse
Dec 8, 2025

Uh oh!

There was an error while loading. Please reload this page.

Merged

gh-139946: distinguish stdout or stderr when colorizing output in argparse #140495

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
6 commits
Select commit Hold shift + click to select a range
1c6c898
fix: distinguish stdout or stderr when colorizing output in argparse
frostming Oct 23, 2025
6d10257
📜🤖 Added by blurb_it.
blurb-it[bot] Oct 23, 2025
6c02905
fix: make _get_formatter to take file argument to avoid calling set_c…
frostming Oct 27, 2025
8ed66a2
add tests for the change
frostming Oct 27, 2025
8518870
fix: handle backward-compatibility for format_* methods
frostming Nov 12, 2025
6dd3d3d
Merge branch 'main' into fix/colorize-argparse
savannahostrowski Dec 8, 2025
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

44 changes: 30 additions & 14 deletions 44 Lib/argparse.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,8 @@
import os as _os
import re as _re
import sys as _sys

from gettext import gettext as _, ngettext
from gettext import gettext as _
from gettext import ngettext

SUPPRESS = '==SUPPRESS=='

Expand Down Expand Up @@ -191,10 +191,10 @@ def __init__(

self._set_color(False)

def _set_color(self, color):
def _set_color(self, color, *, file=None):
from _colorize import can_colorize, decolor, get_theme

if color and can_colorize():
if color and can_colorize(file=file):
self._theme = get_theme(force_color=True).argparse
self._decolor = decolor
else:
Expand Down Expand Up @@ -1675,7 +1675,7 @@ def _get_optional_kwargs(self, *args, **kwargs):
option_strings = []
for option_string in args:
# error on strings that don't start with an appropriate prefix
if not option_string[0] in self.prefix_chars:
if option_string[0] not in self.prefix_chars:
raise ValueError(
f'invalid option string {option_string!r}: '
f'must start with a character {self.prefix_chars!r}')
Expand Down Expand Up @@ -2455,7 +2455,7 @@ def _parse_optional(self, arg_string):
return None

# if it doesn't start with a prefix, it was meant to be positional
if not arg_string[0] in self.prefix_chars:
if arg_string[0] not in self.prefix_chars:
return None

# if the option string is present in the parser, return the action
Expand Down Expand Up @@ -2717,14 +2717,16 @@ def _check_value(self, action, value):
# Help-formatting methods
# =======================

def format_usage(self):
formatter = self._get_formatter()
def format_usage(self, formatter=None):
Comment thread
frostming marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

if formatter is None:
formatter = self._get_formatter()
formatter.add_usage(self.usage, self._actions,
self._mutually_exclusive_groups)
return formatter.format_help()

def format_help(self):
formatter = self._get_formatter()
def format_help(self, formatter=None):
if formatter is None:
formatter = self._get_formatter()

# usage
formatter.add_usage(self.usage, self._actions,
Expand All @@ -2746,9 +2748,9 @@ def format_help(self):
# determine help from format above
return formatter.format_help()

def _get_formatter(self):
def _get_formatter(self, file=None):
formatter = self.formatter_class(prog=self.prog)
formatter._set_color(self.color)
formatter._set_color(self.color, file=file)
return formatter

def _get_validation_formatter(self):
Expand All @@ -2765,12 +2767,26 @@ def _get_validation_formatter(self):
def print_usage(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_usage(), file)
formatter = self._get_formatter(file=file)
try:
usage_text = self.format_usage(formatter=formatter)
except TypeError:
# Backward compatibility for formatter classes that
# do not accept the 'formatter' keyword argument.
usage_text = self.format_usage()
self._print_message(usage_text, file)

def print_help(self, file=None):
if file is None:
file = _sys.stdout
self._print_message(self.format_help(), file)
formatter = self._get_formatter(file=file)
try:
help_text = self.format_help(formatter=formatter)
except TypeError:
# Backward compatibility for formatter classes that
# do not accept the 'formatter' keyword argument.
help_text = self.format_help()
self._print_message(help_text, file)

def _print_message(self, message, file=None):
if message:
Expand Down
34 changes: 34 additions & 0 deletions 34 Lib/test/test_argparse.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -7558,6 +7558,40 @@ def test_error_and_warning_not_colorized_when_disabled(self):
self.assertNotIn('\x1b[', warn)
self.assertIn('warning:', warn)

def test_print_help_uses_target_file_for_color_decision(self):
parser = argparse.ArgumentParser(prog='PROG', color=True)
parser.add_argument('--opt')
output = io.StringIO()
calls = []

def fake_can_colorize(*, file=None):
calls.append(file)
return file is None

with swap_attr(_colorize, 'can_colorize', fake_can_colorize):
parser.print_help(file=output)

self.assertIs(calls[-1], output)
self.assertIn(output, calls)
self.assertNotIn('\x1b[', output.getvalue())

def test_print_usage_uses_target_file_for_color_decision(self):
parser = argparse.ArgumentParser(prog='PROG', color=True)
parser.add_argument('--opt')
output = io.StringIO()
calls = []

def fake_can_colorize(*, file=None):
calls.append(file)
return file is None

with swap_attr(_colorize, 'can_colorize', fake_can_colorize):
parser.print_usage(file=output)

self.assertIs(calls[-1], output)
self.assertIn(output, calls)
self.assertNotIn('\x1b[', output.getvalue())


class TestModule(unittest.TestCase):
def test_deprecated__version__(self):
Expand Down
1 change: 1 addition & 0 deletions 1 Misc/NEWS.d/next/Library/2025-10-23-06-38-35.gh-issue-139946.HZa5hu.rst
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Distinguish stdout and stderr when colorizing output in argparse module.
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.