Help with Python 3 UnicodeDecodeError when receiving bytes

2

I have to send the output of an "ipconfig" command using a socket with the check_output method of the subprocess module. This process used to be easy in the Python version 2.7 but in Python 3 everything is more complicated and it shows me a UnicodeDecodeError.

This is the code that sends the bytes:

import socket
import subprocess 

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost",7500))

m = subprocess.check_output('ipconfig')
client.send(m)

Of course, it is not necessary to convert it to bytes to send it because the output of check_output already delivers values in byte format.

Until there is everything right, but the problem occurs in the following code that receives the data since it does not allow me to decode it.

The code that receives the data is the following:

import socket

serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind(("localhost",7500))
serv.listen(1)

conex,direccion = serv.accept()
a = conex.recv(4096)
print(a.decode('utf-8'))

When I execute this code it shows me the following error: in the last line, in which it says "print (a.decode ('utf-8'))", the error that I get is the following:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa2 in position 13: invalid start byte
    
asked by Jhonatan Zu 27.06.2018 в 00:12
source

1 answer

0

What returns subprocess.check_output are effectively bytes, but with a certain encoding, which like all programs in console mode returns the text encoding by means of the active 8-bit code page for the console , possibly cp850.

What you can do is at the client decode the output using the appropriate coding depending on the code page of CMD and then encode it with UTF-8 and send it so that the server always receives UTF-8 and can obtain the object str with a.decode('utf-8') .

import socket
import subprocess 

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 7500))

m = subprocess.check_output('ipconfig')
m = m.decode("cp850").encode("utf-8")
client.send(m)
    
answered by 27.06.2018 / 02:20
source