【发布时间】:2017-06-07 07:36:34
【问题描述】:
我对 python 有初步的了解,但不清楚如何处理二进制编码问题。我正在尝试从 firefox-webextensions 示例中运行示例代码,其中 python 脚本发送由 javascript 程序读取的文本。我一直遇到编码错误。
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 El Capitan 10.11.6、x86 64bit cpu 上运行 python 3.5.1; firefox 开发者版 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'
【问题讨论】:
-
您是否尝试将其转换为如下字符串?sys.stdout.buffer.write(str(encodedMessage['length']))