"a bytes-like object is required" 但我正在使用字节

"a bytes-like object is required" but I am using bytes

使用 Python3 我以二进制模式重新打开了 stdout。之后当我 print("Hello") 它告诉我我需要使用一个类似字节的对象。很公平,它现在处于二进制模式。

但是当我这样做时:

print(b"Some bytes")

仍然得到这个错误:

TypeError: a bytes-like object is required, not 'str'

这是怎么回事?

print() 总是 写入 str 值。它会首先将任何参数转换为字符串,包括字节对象。

来自print() documentation

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

你不能在二进制流上使用 print(),句号。要么直接写入流(使用它的 .write() 方法),要么将流包装在 TextIOWrapper() object 中以处理编码。

这两个都有效:

import sys

sys.stdout.write(b'Some bytes\n')  # note, manual newline added

from io import TextIOWrapper
import sys

print('Some text', file=TextIOWrapper(sys.stdout, encoding='utf8'))