python
type_error
ai_generated
true
TypeError: a bytes-like object is required, not 'str' in capsys.readouterr()
ID: python/pytest-capture-output-binary
80%Fix Rate
82%Confidence
0Evidence
2026-02-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.11 | active | — | — | — |
Root Cause
Using capsys (which captures text) to capture binary output from sys.stdout.buffer, causing a type mismatch when the code writes bytes.
generic中文
使用 capsys(捕获文本)来捕获来自 sys.stdout.buffer 的二进制输出,当代码写入字节时导致类型不匹配。
Workarounds
-
90% success
Use capfd (capture file descriptors) instead of capsys to capture both text and binary output: out, err = capfd.readouterr()
-
85% success
If the output is binary, use sys.stdout.buffer.write() and capture with capfd, then decode as needed.
Dead Ends
Common approaches that don't work:
-
50% fail
Using capfd instead of capsys may work for binary but fails if the test also needs to capture text from sys.stdout.
-
40% fail
Decoding bytes to str before assertion may mask encoding issues in the output.