Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么sys.stdin.read(4).encode(';utf-8';)返回的字节数超过4个?_Python - Fatal编程技术网

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

Python 为什么sys.stdin.read(4).encode(';utf-8';)返回的字节数超过4个?,python,Python,我通过Chrome/JavaScript sendNativeMessage函数将一个JSON对象从Chrome传递到Python应用程序的stdin 有时,下面的代码可以工作。其他时候(我相信更大的消息),它不起作用。我不确定我做错了什么,但我要说的是,有时sys.stdin.read(4).encode('utf-8')似乎读取了7个字节而不是指定的4个字节,这时它会出现“struct.error:unpack需要长度为4的字节对象”消息 有人能告诉我我做错了什么吗 # On Windows

我通过Chrome/JavaScript sendNativeMessage函数将一个JSON对象从Chrome传递到Python应用程序的stdin

有时,下面的代码可以工作。其他时候(我相信更大的消息),它不起作用。我不确定我做错了什么,但我要说的是,有时sys.stdin.read(4).encode('utf-8')似乎读取了7个字节而不是指定的4个字节,这时它会出现“struct.error:unpack需要长度为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

非ASCII字符在UTF-8中不作为单个字节编码。我应该以不同的方式编码这些字符吗?还是以完全不同的方式处理数据?在这一点上我有点不知所措——道歉;我是Python新手。@flatsix81:如果你有一个压缩整数,你肯定不想对包含压缩整数的字符串进行任何编码/解码。按照tommi的建议读取原始字节,然后解包,然后读取消息的其余部分,然后使用utf-8进行解码(即,将字节转换为unicode),如果它们是使用utf-8编码的(即,将unicode转换为字节)。这很有效!太神了为了解决这个问题,我已经用头撞桌子好几个小时了。再次感谢!