使用 Telnet.write() 的类型错误
TypeError using Telnet.write()
我有以下代码:
try:
tn = Telnet(host, str(port))
except Exception as e:
print("Connection cannot be established", e)
traceback.print_exc()
print("You are connected")
tn.write('command?'+'\r\n')
while True:
line = tn.read_until("\n")
当我在机器 X 上 运行 这段代码时,一切正常,但是当我尝试 运行 不同机器上的相同代码时,我最终遇到以下错误:
Traceback (most recent call last):
File
"C:/Users/admin/Documents/Projects/terminalManager/terminalManager.py", line 50, in <module>
terminalManager()
File
"C:/Users/admin/Documents/Projects/terminalManager/terminalManager.py", line 16, in __init__
self.connect(terminalBganIp, terminalBganPort)
File "C:/Users/admin/Documents/Projects/terminalManager/terminalManager.py", line 34, in connect
tn.write('AT_IGPS?'+'\r\n')
File "C:\Program Files (x86)\Python\Python3.6.1\lib\telnetlib.py", line 287, in write
if IAC in buffer:
TypeError: 'in <string>' requires string as left operand, not bytes
是我做错了什么还是第二台机器有问题?
编辑:
当我在我的第二台机器上使用 IDLE 调试器时,一切正常。 运行正常时似乎无法正常工作,我能做些什么来解决这个问题吗?
尝试做:
tn.write(('command?'+'\r\n').encode())
通常套接字处理字节而不是字符串,错误可能与此有关,希望这能有所帮助。
我不敢相信相同的代码在具有相同 python 版本的另一台机器上为您工作。
您的问题正是异常所说的 TypeError: 'in <string>' requires string as left operand, not bytes
。您需要提供 bytes
到 tn.write
而不是 string
.
您可以通过 encode
:
将字符串转换为字节
command = "command?" + "\r\n"
tn.write(command.encode("ascii"))
编辑:好吧,有人先于我 :D
我有以下代码:
try:
tn = Telnet(host, str(port))
except Exception as e:
print("Connection cannot be established", e)
traceback.print_exc()
print("You are connected")
tn.write('command?'+'\r\n')
while True:
line = tn.read_until("\n")
当我在机器 X 上 运行 这段代码时,一切正常,但是当我尝试 运行 不同机器上的相同代码时,我最终遇到以下错误:
Traceback (most recent call last):
File
"C:/Users/admin/Documents/Projects/terminalManager/terminalManager.py", line 50, in <module>
terminalManager()
File
"C:/Users/admin/Documents/Projects/terminalManager/terminalManager.py", line 16, in __init__
self.connect(terminalBganIp, terminalBganPort)
File "C:/Users/admin/Documents/Projects/terminalManager/terminalManager.py", line 34, in connect
tn.write('AT_IGPS?'+'\r\n')
File "C:\Program Files (x86)\Python\Python3.6.1\lib\telnetlib.py", line 287, in write
if IAC in buffer:
TypeError: 'in <string>' requires string as left operand, not bytes
是我做错了什么还是第二台机器有问题?
编辑:
当我在我的第二台机器上使用 IDLE 调试器时,一切正常。 运行正常时似乎无法正常工作,我能做些什么来解决这个问题吗?
尝试做:
tn.write(('command?'+'\r\n').encode())
通常套接字处理字节而不是字符串,错误可能与此有关,希望这能有所帮助。
我不敢相信相同的代码在具有相同 python 版本的另一台机器上为您工作。
您的问题正是异常所说的 TypeError: 'in <string>' requires string as left operand, not bytes
。您需要提供 bytes
到 tn.write
而不是 string
.
您可以通过 encode
:
command = "command?" + "\r\n"
tn.write(command.encode("ascii"))
编辑:好吧,有人先于我 :D