【问题标题】:Why Do I Get This Error Message When Using Telnet In Python Shell [duplicate]为什么在 Python Shell 中使用 Telnet 时会收到此错误消息 [重复]
【发布时间】:2014-06-06 22:02:15
【问题描述】:

我遇到了一个问题,因为我正在尝试使用 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

请有人告诉我为什么会收到错误消息以及如何修复它?

谢谢

【问题讨论】:

标签: python macos raspberry-pi telnet


【解决方案1】:
TypeError: Type str doesn't support the buffer API

这是一个棘手的错误 - 它告诉您足以提供帮助,但前提是您知道问题所在。

在 Python 3 中,字节之间存在明显差异:

b'This is a byte string'

还有常规的 unicode,或str 字符串:

'This is a regular unicode string'

这是一个重要的区别,当美国是 Internet 上唯一的国家,而 ASCII 是网络的编码规范时,没有人真正关心这一点。但是现在我们需要表示的字符数量远远超过 0-254 个字符。这就是unicode 的用武之地。

现在,在大多数语言中,它们有点像二进制数据一样抛出字符串,反之亦然,这可能会导致各种奇怪和意想不到的怪癖。 Python3 试图做正确的事(tm),并通过决定明确区分字节和文本而在很大程度上取得了成功。字节只是二进制数据,您可以将这些字节解码为您想要的任何编码(UTF、ASCII、一些疯狂的东西)——但只有在向用户显示时才应该这样做。否则,您将传递二进制数据。

我告诉你这个故事是为了告诉你这个:

bot.read_until("login: ", timeout=None)

具有以下 unicode str - "login: "str不支持缓冲接口,但bytes支持。

使用以下首字母缩写词帮助您记住:BADTIE

B ytes
A 重新
D 编码
T ext

电子编码

写成bot.read_until("login: ".encode(), timeout=None)您还需要修复其他字符串。另一个应该可行的选择是将其更改为b"login: ",但我从未尝试过。

【讨论】:

  • 看起来你有逆问题 - bytes 它期望 str。或者"\n" 应该是b"\n"
  • 当我这样做时,我收到错误消息:raceback(最后一次调用):文件“/Users/kiancross/Desktop/PROJECTS/RASPBERRY_PI/ROBOT/CONTROLLER_GUI/RPi_BOT_CONTROLLER.py”,第 17 行,在 bot.write(user + b"\n") TypeError: Can't convert 'bytes' object to str implicitly
  • -你知道我为什么得到上面的错误代码吗?
  • 在该行之前尝试print(type(user))。错误信息很清楚。
  • -我已经这样做了,但我仍然收到相同的错误消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-15
  • 1970-01-01
  • 2013-12-02
相关资源
最近更新 更多