-1

I'm a complete newbie in Python, but I have been programming for fun in (Liberty-)Basic since about 1980.

Using Python 3.5.2 I was testing this script:

import time, telnetlib

host    = "dxc.ve7cc.net"
port    = 23
timeout = 9999

try:
    session = telnetlib.Telnet(host, port, timeout)
except socket.timeout:
    print ("socket timeout")
else:
    session.read_until("login: ")
    session.write("on0xxx\n")
    output = session.read_some()
    while output:
        print (output)
        time.sleep(0.1)  # let the buffer fill up a bit
        output = session.read_some()

Can anyone tell me why I get the TypeError: a bytes-like object is required, not 'str' and how I can solve it?

ON5MF Jurgen
  • 113
  • 2
  • 7
  • Possible duplicate of [TypeError: a bytes-like object is required, not 'str'](http://stackoverflow.com/questions/33003498/typeerror-a-bytes-like-object-is-required-not-str) – Marcus Müller Apr 17 '17 at 21:32

2 Answers2

2

In Python 3 (but not in Python 2), str and bytes are distinct types that can't be mixed. You can't write a str directly to a socket; you have to use bytes. Simply prefix the string literal with b to make it a bytes literal.

session.write(b"on0xxx\n")
dan04
  • 87,747
  • 23
  • 163
  • 198
1

Unlike in Python 2.x, where you don't need to encode the data sent through the net, you have to in Python 3.x. So everything you want to send needs to be encoded with the .encode() function. Everything you receive needs to be decoded with .decode().