gpt4 book ai didi

没有 ascii 编码和 b 前缀的 Python3 : Is there a way to use telnetlib like in python2,?

转载 作者:行者123 更新时间:2023-12-04 15:34:32 28 4
gpt4 key购买 nike

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

我注意到我需要在 read_until() 前加上字母 b,并且我需要在字符串上使用 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 的问题。这比查找所有读写操作更容易。

关于没有 ascii 编码和 b 前缀的 Python3 : Is there a way to use telnetlib like in python2,?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60176138/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com