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