René's URL Explorer Experiment


Title: Errors raised in argparse are colorized when redirecting stderr to a file · Issue #139946 · python/cpython · GitHub

Open Graph Title: Errors raised in argparse are colorized when redirecting stderr to a file · Issue #139946 · python/cpython

X Title: Errors raised in argparse are colorized when redirecting stderr to a file · Issue #139946 · python/cpython

Description: Bug report Bug description: (Some) Errors raised in argparse will be colorized when redirecting stderr to a file. Requirements: Errors redirected to a file are not colorized Unittest added to cover the case of error and redirecting of st...

Open Graph Description: Bug report Bug description: (Some) Errors raised in argparse will be colorized when redirecting stderr to a file. Requirements: Errors redirected to a file are not colorized Unittest added to cover...

X Description: Bug report Bug description: (Some) Errors raised in argparse will be colorized when redirecting stderr to a file. Requirements: Errors redirected to a file are not colorized Unittest added to cover...

Opengraph URL: https://github.com/python/cpython/issues/139946

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Errors raised in argparse are colorized when redirecting stderr to a file","articleBody":"# Bug report\n\n### Bug description:\n\n(Some) Errors raised in argparse will be colorized when redirecting stderr to a file. \n\nRequirements:\n\n1. Errors redirected to  a file are not colorized\n2. Unittest added to cover the case of error and redirecting of stderr\n\nThe most minimal example can be taken from `calendar` from the stdlib. \n\nWorks as expected with the color displayed correctly.\n\n```bash\n./python.exe -m calendar 2020 01 01\n```\n\nRedirecting stderr\n\n```bash\n./python.exe -m calendar 2020 01 01 2\u003e err\ncat -v err\n^[[1;34musage: ^[[0m^[[1;35mpython.exe -m calendar^[[0m [^[[32m-h^[[0m] [^[[32m-w ^[[33mWIDTH^[[0m] [^[[32m-l ^[[33mLINES^[[0m] [^[[32m-s ^[[33mSPACING^[[0m] [^[[32m-m ^[[33mMONTHS^[[0m] [^[[32m-c ^[[33mCSS^[[0m] [^[[32m-L ^[[33mLOCALE^[[0m] [^[[32m-e ^[[33mENCODING^[[0m] [^[[32m-t ^[[33m{text,html}^[[0m] [^[[32m-f ^[[33mFIRST_WEEKDAY^[[0m] ^[[32m[year]^[[0m ^[[32m[month]^[[0m\npython.exe -m calendar: error: unrecognized arguments: 01\n```\n\nRedirecting stdout will trigger the \"correct\" behavior\n\n```bash\n./python.exe -m calendar 2020 01 01 \u003eout 2\u003e err\n(zatters-314) mkocher@zudio cpython % cat -v err\nusage: python.exe -m calendar [-h] [-w WIDTH] [-l LINES] [-s SPACING]\n                              [-m MONTHS] [-c CSS] [-L LOCALE] [-e ENCODING]\n                              [-t {text,html}] [-f FIRST_WEEKDAY]\n                              [year] [month]\npython.exe -m calendar: error: unrecognized arguments: 01\n```\n\nObservations\n\n\n1. Calling `can_colorize(file=None)` assumes that the stdout is used when `file=None` This implicit use of `can_colorize()` makes the code hard to reason about. \n1. Calling `_set_color` always assumes stdout. \n1. Calling `self.print_usage(_sys.stderr)` is breaking the assumption that stdout is being used. \n1. global ENV var design choice make data flow in the code confusing to debug. Depending on how your argparse code is written and the pattern/style of raising errors, some errors raised are being colorized properly by traceback layer. For example, using `parser.error(...)` or `raise ArgumentTypeError(...)` vs a `raise ValueError()` within your application code.\n1. I think users are going to be a bit confused when setting `ArgumentParser(color=False)` and the error (might) still be colorized (because of the traceback layer determining if it should be colorized).  It is documented that configure for traceback is done via ENV vars, but it's not particular clear how the config of these components overlap. \n1. the specific error is not colorized (`python.exe -m calendar: error: unrecognized arguments: 01`) but the usage is?  \n\n\nStand alone example for debugging:\n\n```python\nimport sys\nfrom argparse import ArgumentParser, ArgumentTypeError\n\n\ndef validate_lower(sx: str) -\u003e str:\n    if any(not s.islower() for s in sx):\n        # this will be handled from within argparse.\n        # redirecting stderr will still have colorized ascii\n        raise ArgumentTypeError(f\"{sx} contains a lowercase string\")\n    return sx\n\n\ndef get_parser() -\u003e ArgumentParser:\n    p = ArgumentParser(description=\"Testing\", color=True)\n    f = p.add_argument\n    f('-m', '--max-records', type=int, help=\"Max number of records\", required=True)\n    f('-n', '--name', type=validate_lower, help=\"User Name\", required=True)\n    f('-t', '--trigger-error', action='store_true', help=\"Trigger error\", required=False)\n    return p\n\ndef main(argv: list[str]) -\u003e int:\n    p = get_parser()\n    pa = p.parse_args(argv)\n    if pa.trigger_error:\n        # will be colorized by traceback, must be configured by ENV vars to disable\n        raise ValueError(\"Trigger an error\")\n\n    # this is also a common usage to raise an error\n    #p.error(\"Error case\")\n    print(f\"Completed running {pa}\")\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main(sys.argv[1:]))\n```\n\n### CPython versions tested on:\n\n3.14\n\n### Operating systems tested on:\n\nmacOS\n\n\u003c!-- gh-linked-prs --\u003e\n### Linked PRs\n* gh-140495\n* gh-140695\n* gh-142398\n\u003c!-- /gh-linked-prs --\u003e\n","author":{"url":"https://github.com/mpkocher","@type":"Person","name":"mpkocher"},"datePublished":"2025-10-11T09:16:19.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":3},"url":"https://github.com/139946/cpython/issues/139946"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:a21789e9-4b27-c211-6c4d-cef624851ba4
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idE0EA:37FB75:92481B6:C1E2C0B:696E0CC4
html-safe-nonce817ba5a9a83c7501e9748e97b03424c83afafba2a26e171289f2c17841436a8e
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFMEVBOjM3RkI3NTo5MjQ4MUI2OkMxRTJDMEI6Njk2RTBDQzQiLCJ2aXNpdG9yX2lkIjoiNDgwMTE2MjkzOTE2MDQ2NDU4MCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmace71ba22e105fb91e416ec8461eb46994cd79b03e3ff5c6d75864a73ea524f809
hovercard-subject-tagissue:3505494037
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/139946/issue_layout
twitter:imagehttps://opengraph.githubassets.com/ed919e1b2b6ba52062829f8d3c15c15d0ea04d7407585187c20290c17b8857a9/python/cpython/issues/139946
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/ed919e1b2b6ba52062829f8d3c15c15d0ea04d7407585187c20290c17b8857a9/python/cpython/issues/139946
og:image:altBug report Bug description: (Some) Errors raised in argparse will be colorized when redirecting stderr to a file. Requirements: Errors redirected to a file are not colorized Unittest added to cover...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamempkocher
hostnamegithub.com
expected-hostnamegithub.com
None0b1760aa20e1a810eba6245d04e3885be7363dfe08d08b61f605c852359472e0
turbo-cache-controlno-preview
go-importgithub.com/python/cpython git https://github.com/python/cpython.git
octolytics-dimension-user_id1525981
octolytics-dimension-user_loginpython
octolytics-dimension-repository_id81598961
octolytics-dimension-repository_nwopython/cpython
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id81598961
octolytics-dimension-repository_network_root_nwopython/cpython
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release84090305cd10c2b140bf307f69f57f0892b4f215
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/python/cpython/issues/139946#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F139946
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub SparkBuild and deploy intelligent appshttps://github.com/features/spark
GitHub ModelsManage and compare promptshttps://github.com/features/models
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
GitHub SponsorsFund open source developershttps://github.com/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/accelerator
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2Fpython%2Fcpython%2Fissues%2F139946
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=python%2Fcpython
Reloadhttps://github.com/python/cpython/issues/139946
Reloadhttps://github.com/python/cpython/issues/139946
Reloadhttps://github.com/python/cpython/issues/139946
python https://github.com/python
cpythonhttps://github.com/python/cpython
Please reload this pagehttps://github.com/python/cpython/issues/139946
Notifications https://github.com/login?return_to=%2Fpython%2Fcpython
Fork 33.9k https://github.com/login?return_to=%2Fpython%2Fcpython
Star 71.1k https://github.com/login?return_to=%2Fpython%2Fcpython
Code https://github.com/python/cpython
Issues 5k+ https://github.com/python/cpython/issues
Pull requests 2.1k https://github.com/python/cpython/pulls
Actions https://github.com/python/cpython/actions
Projects 31 https://github.com/python/cpython/projects
Security Uh oh! There was an error while loading. Please reload this page. https://github.com/python/cpython/security
Please reload this pagehttps://github.com/python/cpython/issues/139946
Insights https://github.com/python/cpython/pulse
Code https://github.com/python/cpython
Issues https://github.com/python/cpython/issues
Pull requests https://github.com/python/cpython/pulls
Actions https://github.com/python/cpython/actions
Projects https://github.com/python/cpython/projects
Security https://github.com/python/cpython/security
Insights https://github.com/python/cpython/pulse
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/139946
New issuehttps://github.com/login?return_to=https://github.com/python/cpython/issues/139946
#140495https://github.com/python/cpython/pull/140495
Errors raised in argparse are colorized when redirecting stderr to a filehttps://github.com/python/cpython/issues/139946#top
#140495https://github.com/python/cpython/pull/140495
3.14bugs and security fixeshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.14%22
3.15new features, bugs and security fixeshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.15%22
stdlibStandard Library Python modules in the Lib/ directoryhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22stdlib%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
https://github.com/mpkocher
https://github.com/mpkocher
mpkocherhttps://github.com/mpkocher
on Oct 11, 2025https://github.com/python/cpython/issues/139946#issue-3505494037
gh-139946: distinguish stdout or stderr when colorizing output in argparse #140495https://github.com/python/cpython/pull/140495
GH-139946: Colorize error and warning messages in argparse #140695https://github.com/python/cpython/pull/140695
[3.14] GH-139946: Document argparse includes color codes when redirecting to stderr to file #142398https://github.com/python/cpython/pull/142398
3.14bugs and security fixeshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.14%22
3.15new features, bugs and security fixeshttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%223.15%22
stdlibStandard Library Python modules in the Lib/ directoryhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22stdlib%22
type-bugAn unexpected behavior, bug, or errorhttps://github.com/python/cpython/issues?q=state%3Aopen%20label%3A%22type-bug%22
Argparse issueshttps://github.com/orgs/python/projects/5
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.