Issue
I have a script that use the module socket inside a python2 script. I would like to upgrade it to a python3 script.
After searching Difference between Python3 and Python2 - socket.send data and Python socket.send encoding, i haven't succed to upgrade to python3.
A similar post TypeError: a bytes-like object is required, not 'str' describes the method sendto
that seem to work in python3, but I have no port on this example...
Here is the connection method:
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sys.stderr.write("Waiting for connect to %s\n" % (self.uds_filename,))
while 1:
try:
sock.connect(self.uds_filename)
except socket.error as e:
if e.errno == errno.ECONNREFUSED:
time.sleep(0.1)
continue
sys.stderr.write("Unable to connect socket %s [%d,%s]\n"
% (self.uds_filename, e.errno,
errno.errorcode[e.errno]))
sys.exit(-1)
break
print("CONNECTED")
self.webhook_socket = sock
And this is the send method:
def send(self, message):
self.webhook_socket.send("%s\x03" % (message)) # message is type 'str'
The question is: How to translate it correctly. It is send to a Klipper service (3D printing), I don t want to change the server side, only the client side (theses two methods) to python3.
This working script can be found at https://github.com/Klipper3d/klipper/blob/master/scripts/whconsole.py
Because this script interract with specific hardware (3D printer), I will tests your answers. The problem I had by testing solutions of python3 was no answers at all without any errors...
By changing the send method to
def send(self, message):
self.webhook_socket.send(message.encode())
There is just no answer from the klipper server, it may receive as valid only the python2 format. How to send the exact same message (not a working substitute but a replica) ???
EDIT: Answer from Yarin_007:
sock.send(("%s\x03" % (message)).encode()) # Python 2
sock.send(message.encode()+bytes([0x03])) # Python 3
Solution
You mean you want to send some ascii text and few bytes in python 3?
it's as simple as
self.webhook_socket.send("your string".encode() + bytes([0x03])) # or a longer list of bytes
You can literally only send bits over packets.... that's just the reality. you can't send "str objects". What humans do to deal with this is either serialization, or, in this case, encoding. The software at the other side only sees a list of bytes. it's not until you "parse" it and decode them (if they're text) that they make sense.
That's a great improvement imo in python 3 over 2 - 2 would implicitly convert the string to a bytes sequence, while in 3 you've got to be explicit.
see also bytearray
I think you simply forgot to append the 0x03 byte at the end of the data. (which is crucial for the protocol, I assume.) (it could be the etx terminator.
Are you sending a json? like:
Answered By - Yarin_007
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.