[英]why is sys.stdin.read(4).encode('utf-8') returning more than 4 bytes?
我正在通过Chrome / JavaScript sendNativeMessage函数将JSON对象从Chrome传递到我的Python应用的标准输入。
有时,下面的代码有效。 其他时间(我相信较大的消息),它不起作用。 我不确定自己在做什么错,但是我会说有时候sys.stdin.read(4).encode('utf-8')似乎读取7个字节,而不是指定的4个字节,那是它以“ struct.error:解包需要长度为4的字节对象”消息中断。
有人可以让我知道我在做什么错吗?
# On Windows, the default I/O mode is O_TEXT. Set this to O_BINARY
# to avoid unwanted modifications of the input/output streams.
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
# Read the message length (first 4 bytes).
#for line in sys.stdin:
text_length_bytes = sys.stdin.read(4).encode('utf-8')
logging.info( text_length_bytes )
# Unpack message length as 4 byte integer.
text_length = struct.unpack('i', text_length_bytes)[0]
logging.info( text_length )
# Read the text of the message.
text = json.loads( sys.stdin.read(text_length) )
一个Unicode字符可能包含多个字节:
In [4]: len('ü'.encode('utf-8'))
Out[4]: 2
当您想将这4个字节解码为整数时,您可能首先希望将它们从stdin读取为字节(而不是str):
In [8]: type(sys.stdin.read(4))
aoeu
Out[8]: str
In [9]: type(sys.stdin.buffer.read(4))
aoeu
Out[9]: bytes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.