python / python/cpython

subprocess: `CalledProcessError.__str__` crashes when returncode is None

Open
#153,970 10 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib topic-subprocess triaged type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Calling str() on a CalledProcessError crashes if its returncode is None.

The __str__ method uses if self.returncode and self.returncode < 0 for the "died with a signal" case, and otherwise formats the return code with %d. When returncode is None, that first check is falsy, so it falls through to the %d branch, and %d can't format None, so it raises TypeError. Having the exception's own string representation blow up is a pretty bad way to fail.

import subprocess
err = subprocess.CalledProcessError(None, "cmd")
str(err)  # TypeError: %d format: a real number is required, not NoneType

The fix is to check for returncode is None before the %d branch and return a plain message instead.

Found while going through devdanzin's audit of the standard library, item 9: https://gist.github.com/devdanzin/3198710e3c0128fda5e0a7b4e0768e5f

Linked PRs
  • gh-153971
  • gh-155923
  • gh-155924
  • gh-155931

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at subprocess.CalledProcessError.str and reproduce the example from the issue with a None returncode. Add coverage for the failing representation and confirm that str(err) returns a plain message without raising; review the linked PRs before starting because work is already listed against this issue.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
operating-systems
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.