使用Python3,我以二进制模式重新打开了stdout。之后,当我 print("Hello")
时,它告诉我需要使用类似字节的对象。很公平,现在处于二进制模式。
但是当我这样做时:
print(b"Some bytes")
我仍然收到此错误:
TypeError: a bytes-like object is required, not 'str'
这是怎么回事?
最佳答案
print()
始终写入str
值。它首先将所有参数转换为字符串,包括字节对象。
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/