python - "a bytes-like object is required"但我使用的是字节

标签 python python-3.x printing bytesio

使用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'))

关于python - "a bytes-like object is required"但我使用的是字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47328075/

相关文章:

python - 在 tastypie 中处理多个查询参数

python - 如果第二列与给定的 Pandas 列表匹配,则替换数据框列中的值

python - 将过滤器链接在一起

python - 如何在python中分别计算每个簇的Silhouette Score

javascript - 网页打印按钮和设置

python - 如何使用 pdfrw 库编辑可编辑的 pdf?

python-3.x - 可视化链接攻击的最佳方式是什么

python - 有没有办法让这个逆阶乘代码更有效地运行

r - 打印数据框时如何不重复相同的值?

android - 在android中,如何在没有打印机插件的情况下打印