I have a rudimentary grasp of python but am not clear on dealing with binary encoding issues. I am trying to run sample code from a firefox-webextensions example in which a python script sends text that is read by a javascript program. I keep encountering encoding errors.
The python code is:
#! /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'])
The error trace (displayed in firefox console) is:
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
Running python 3.5.1 on OS X El Capitan 10.11.6, x86 64bit cpu; firefox developer ed 52.0
The python script I am using, as shown above, is minimized from the original at https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Native_messaging
I also tried:
sys.stdout.buffer.write(encodedMessage['length'])
sys.stdout.buffer.write(encodedMessage['content'])
which generated:
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'