编码:TypeError:写入()参数必须是str,而不是字节
我对python有基本的把握,但在处理二进制编码问题时并不清楚。我试图从firefox-webextensions示例中运行示例代码,其中python脚本发送由JavaScript程序读取的文本。我一直在遇到编码错误。编码:TypeError:写入()参数必须是str,而不是字节
的Python代码是:
#! /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
import sys, json, struct
text = "pong"
encodedContent = json.dumps(text)
encodedLength = struct.pack('@I', len(encodedContent))
encodedMessage = {'length': encodedLength, 'content': encodedContent}
sys.stdout.write(encodedMessage['length'])
sys.stdout.write(encodedMessage['content'])
的错误跟踪(显示在Firefox控制台)是:
stderr output from native app chatX: Traceback (most recent call last):
stderr output from native app chatX: File "/Users/inchem/Documents/firefox addons/py/chatX.py", line 10, in <module>
stderr output from native app chatX: sys.stdout.write(encodedMessage['length'])
stderr output from native app chatX: TypeError: write() argument must be str, not bytes
在OS X埃尔卡皮坦10.11.6运行蟒3.5.1,86的64位中央处理器;火狐显影剂编52.0
我使用Python脚本,如上所示,是从原始最小化在 https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Native_messaging
我也尝试:
sys.stdout.buffer.write(encodedMessage['length'])
sys.stdout.buffer.write(encodedMessage['content'])
其产生:
stderr output from native app chatX: sys.stdout.buffer.write(encodedMessage['content'])
stderr output from native app chatX: TypeError: a bytes-like object is required, not 'str'
该示例可能是Python 2兼容的,但Python 3中的内容已更改。
要生成长度的二进制表示为字节与此:
encodedLength = struct.pack('@I', len(encodedContent))
它不是可打印的。你可以通过一个二进制流套接字流来写它,但不是通过stdout
这是一个文本流。
使用buffer
的技巧(如How to write binary data in stdout in python 3?解释)是好的,但仅适用于二进制部分(注意,您收到错误消息的文本部分现在):
sys.stdout.buffer.write(encodedMessage['length'])
对于文本部分,只写stdout
:
sys.stdout.write(encodedMessage['content'])
,或者使用与sys.stdout.buffer
字符串字节转换:
sys.stdout.buffer.write(bytes(encodedMessage['content'],"utf-8"))
在写入stdout/stderr之前,您需要确保输入是str(unicode)。
在你的榜样:
sys.stdout.write(encodedMessage['length'].decode('utf8'))
sys.stdout.write(encodedMessage['content'])
你可以看到,type(encodedLength))
是bytes
而type(encodedContent)
是str
。
请阅读the following answer约字节串VS在python3.X更多信息
非常有帮助。谢谢。 –
你试图将其转换为字符串,像下面?sys.stdout.buffer.write(STR(encodedMessage [“长度”]) ) – Shiping