有没有办法通过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,因为这是唯一的主要更改。
谢谢!
您可以在中编写自己的子类 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 telnetlib
来import encodingtelnetlib as telnetlib
。这比查找每个读取和写入要容易。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句