我有以下代码:
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调试器时,一切正常。它似乎在正常运行时不起作用,我有什么办法可以解决这个问题吗?
答案 0 :(得分:4)
我无法相信在具有相同python版本的另一台计算机上,相同的代码正在为您工作。
您的问题正是Exception所说的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
答案 1 :(得分:1)
尝试:
tn.write(('command?'+'\r\n').encode())
通常套接字工作超过字节而不是字符串,错误可能与此有关,希望这可以帮助。