为什么在Python Shell中使用Telnet时出现此错误消息
我遇到了一个问题,我想用telnet连接我的树莓派,但是在输入用户名的时候出现了错误,下面是我复制的错误信息。
#IMPORTS
from tkinter import *
import time
import telnetlib
import sys
import getpass
import tkinter.messagebox
#TELNET
user = input("Please Enter Your Username: ")
time.sleep(0.4)
pass_ = input("Please Enter Your Password: ")
bot = telnetlib.Telnet("192.168.1.128")
bot.read_until("login: ")
bot.write(user + "\n")
bot.read_until("Password: ")
bot.write(pass_ + "\n")
bot.write("cd PiBits/ServoBlaster")
#DEFINITIONS
#STUFF
master = Tk()
#LEFT
left = Scale(master,from_=0,to=249,length=550,width=25,tickinterval=152,sliderlength=30)
left.pack()
left.set(152)
left.grid(row=0, column=2)
#RIGHT
right = Scale(master,from_=0,to=249,length=550,width=25,tickinterval=152,sliderlength=30)
right.pack()
right.set(152)
right.grid(row=0, column=12)
#MIDDLE
mid = Scale(master,from_=0,to=249,length=550,width=25,tickinterval=152,sliderlength=30)
mid.pack()
mid.set(152)
mid.grid(row=0, column=7)
#RUN CANVAS
mainloop()
我收到以下错误信息:
Traceback (most recent call last):
File "/Users/kiancross/Desktop/PROJECTS/RASPBERRY_PI/ROBOT/CONTROLLER_GUI/RPi_BOT_CONTROLLER.py", line 16, in <module>
bot.read_until("login: ", timeout=NONE)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/telnetlib.py", line 304, in read_until
i = self.cookedq.find(match)
TypeError: Type str doesn't support the buffer API
请问有人能告诉我为什么会出现这个错误信息,以及我该怎么解决吗?
谢谢
1 个回答
2
TypeError: Type str doesn't support the buffer API
'This is a regular unicode string'
这个错误有点棘手——它告诉你一些信息,能帮到你,但前提是你得知道问题出在哪里。
在Python 3中,字节(bytes)和普通的unicode字符串(str
)之间有明显的区别:
b'This is a byte string'
这是一个重要的区别,之前在美国是互联网的唯一国家,大家也不太在意这个问题,因为当时网络上主要用的是ASCII编码。但现在我们需要表示的字符已经远远超过0到254了,这时候就需要用到unicode了。
在大多数编程语言中,字符串和二进制数据常常被混用,这样会导致各种奇怪和意想不到的问题。Python 3努力做到正确的区分,基本上成功了,它明确区分了字节和文本。字节只是二进制数据,你可以把这些字节解码成你想要的任何编码(比如UTF、ASCII,或者其他奇怪的编码)——但你应该只在展示给用户的时候才这么做。否则,你传递的就是二进制数据。
我告诉你这个故事是为了让你明白:
bot.read_until("login: ", timeout=None)
有一个unicode str
——"login: "
。str
不支持缓冲接口,但bytes
支持。
用下面这个缩写来帮助你记住:BADTIE
B ytes
A re
D ecoded
T ext
I s
E ncoded
然后像这样写:bot.read_until("login: ".encode(), timeout=None)
。你还需要修正其他的字符串。另一个可行的选项是直接把它改成b"login: "
,但我没试过这个。