s.sendall(filename + "\r\n") TypeError: a bytes-like object is required, not 'str'

Chris Angelico rosuav at gmail.com
Wed Jun 19 10:57:56 EDT 2019


On Thu, Jun 20, 2019 at 12:31 AM vakul bhatt <vakulb5678 at gmail.com> wrote:
>
> Hi Team,
>
> i m new to python, running below program, getting error
> Python Version : 3.7 32bit for windows
> Program:
> ============================
> #simple Goopher client
>
> import socket, sys
>
> port = 70
> host = sys.argv[1]
> filename = sys.argv[2]
>
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.connect((host, port))
>
> s.sendall(filename + "\r\n")
>
> while 1:
>   buf = s.recv(2048)
>   if not len(buf):
>     break
>   sys.stdout.write(buf)
> ============================
>
>
> Error :
>
> ============================
> python goopher.py quux.org /
> Traceback (most recent call last):
>   File "goopher.py", line 13, in <module>
>     s.sendall(filename + "\r\n")
> TypeError: a bytes-like object is required, not 'str'
>

As the message says, you need to have a sequence of bytes, not a text
string. You can't write text to a socket. The way to represent text
using bytes is to use a character encoding such as UTF-8. Try this
instead:

s.sendall(filename.encode("UTF-8") + b"\r\n")

That will send the bytes that make up the UTF-8 representation of the
string, rather than trying to send the abstract characters.

ChrisA



More information about the Python-list mailing list