Home > front end >  Python error: TypeError: sequence item 0: expected a bytes-like object, str found?
Python error: TypeError: sequence item 0: expected a bytes-like object, str found?

Time:01-15

#!/usr/bin/env python3

import socket  
UDP_IP = "127.0.0.1"
UDP_PORT = 3289
sock = socket.socket(socket.AF_INET, # Internet
                        socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
    
while True:
    data, addr = sock.recvfrom(4068) # buffer size is 4068 bytes 
    print("received message: %s" % data)
    out = ["EPSON",
            "Q",        # PacketType (Q for query and C for command)
            "\x03",     # DeviceType(3) (fixed)
            "\x00",     # DeviceNumber(0) (fixed)
            "\x00\x10", # Function(0010h)
            "\x00\x00", # Result (fixed?)
            "\x00\x00", # parameter length Length
            ""]         # command parameter
    l = len("".join(out))
    
    sock.sendto("".join(out), (addr[0], addr[1])) <--- error

I get TypeError: sequence item 0: expected a bytes-like object, str found on the line indicated above. I have also tried

sock.sendto(b"".join(out), (addr[0], addr[1]))

CodePudding user response:

b"".join(out) would expect an iterable of bytes like objects, However, yours are strings. Try

"".join(out).encode()
  •  Tags:  
  • Related