首页 > 解决方案 > Python3:有没有办法像在 python2 中一样使用 telnetlib,没有 ascii 编码和 b 前缀?

问题描述

有没有办法使用 telnetlib 使 python2 脚本与 python3 兼容?

我注意到我需要在 read_until() 前面加上字母 b,并且当我想 write() 时,我需要在字符串上使用 encode('ascii')。

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":/$")

这将帮助我将许多脚本更新到 3.x,因为它是唯一的重大变化。

谢谢!

标签: pythonpython-3.xasciitelnetlib

解决方案


你可以写你自己的子类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

现在它的一个问题是改变import telnetlibimport encodingtelnetlib as telnetlib. 这比找到每次读写都容易。


推荐阅读