python / python/cpython

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

未关闭
#153,970 10 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

stdlib topic-subprocess triaged type-bug
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

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

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 subprocess.CalledProcessError.str 开始,使用 None returncode 复现 issue 中的示例。为失败的表示添加覆盖,并确认 str(err) 返回一条普通消息而不会引发异常;开始前请查看已链接的 PRs,因为相关工作已经列在此 issue 下。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
operating-systems
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
停滞
描述清晰度
描述清楚
新手友好度
30/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。