Is there a way to make python2 scripts compatible with python3 with telnetlib?
I noticed that I need to prefix read_until() with the letter b, and I need to use encode('ascii') on the string when I want to write().
Python2
tn = telnetlib.Telnet("192.168.1.45")
tn.write("ls " + dirname + "\n")
answer = tn.read_until(":/$")
Python3
tn = telnetlib.Telnet("192.168.1.45")
cmd_str = "ls " + dirname + "\n"
tn.write(cmd_str.encode('ascii'))
answer = tn.read_until(b":/$")
This would help me update many scripts to 3.x as it the only major change.
Thanks!
You could write your own subclass in encodingtelnetlib.py
class Telnet(Telnet):
def __init__(self, host=None, port=0,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
encoding='ascii'):
self.encoding = encoding
super().__init__(host, port, timeout)
def write(self, buffer):
if isinstance(buffer, str):
buffer = buffer.encode(self.encoding)
return super().write(buffer)
# and etc.... for other methods
Now its a question of changing import telnetlib
to import encodingtelnetlib as telnetlib
. That's easier than finding every read and write.