[英]Python3: Is there a way to use telnetlib like in python2, without ascii encode and b prefix?
有沒有辦法使用 telnetlib 使 python2 腳本與 python3 兼容?
我注意到我需要在 read_until() 前面加上字母 b,並且當我想 write() 時我需要在字符串上使用 encode('ascii')。
蟒蛇2
tn = telnetlib.Telnet("192.168.1.45")
tn.write("ls " + dirname + "\n")
answer = tn.read_until(":/$")
蟒蛇3
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
。 這比找到每個讀取和寫入更容易。
可能不是因為 Python3 默認使用utf-8
編碼,而 Python2 使用ascii
。 因此,如果您需要一個ascii
編碼的字符串,您需要手動更改編碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.