简体   繁体   English

为什么sys.stdin.read(4).encode('utf-8')返回的字节数超过4个?

[英]why is sys.stdin.read(4).encode('utf-8') returning more than 4 bytes?

I am passing a JSON object from Chrome to my Python app's stdin via the Chrome/JavaScript sendNativeMessage function. 我正在通过Chrome / JavaScript sendNativeMessage函数将JSON对象从Chrome传递到我的Python应用的标准输入。

Sometimes, the below code works. 有时,下面的代码有效。 Other times (I believe on larger messages), it does not work. 其他时间(我相信较大的消息),它不起作用。 I'm not sure what I'm doing wrong, but I will say that sometimes sys.stdin.read(4).encode('utf-8') seems to read 7 bytes instead of the specified 4 bytes, and that's when it breaks with a "struct.error: unpack requires a byte object of length 4" message. 我不确定自己在做什么错,但是我会说有时候sys.stdin.read(4).encode('utf-8')似乎读取7个字节,而不是指定的4个字节,那是它以“ struct.error:解包需要长度为4的字节对象”消息中断。

Can someone let me know what I'm doing wrong here? 有人可以让我知道我在做什么错吗?

# 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) )

One Unicode character may consist of more than one byte: 一个Unicode字符可能包含多个字节:

In [4]: len('ü'.encode('utf-8'))
Out[4]: 2

As you want to decode those 4 bytes as integer, you probably want to read them as bytes (instead of str) from stdin in the first place: 当您想将这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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM