“需要一个类似字节的对象”但我使用的是字节

Tim*_*mmm 2 python printing bytesio python-3.x

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

但是,当我这样做时:

print(b"Some bytes")
Run Code Online (Sandbox Code Playgroud)

仍然收到此错误:

TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)

那是怎么回事?

Mar*_*ers 5

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

print()文档

所有非关键字参数都像 do 一样转换为字符串str()并写入流,由sep分隔,后跟end

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

这些都有效:

import sys

sys.stdout.write(b'Some bytes\n')  # note, manual newline added
Run Code Online (Sandbox Code Playgroud)

from io import TextIOWrapper
import sys

print('Some text', file=TextIOWrapper(sys.stdout, encoding='utf8'))
Run Code Online (Sandbox Code Playgroud)