发生类型错误:不支持Unicode字符串,请编码为字节:'ÿ'

时间:2018-08-13 20:03:05

标签: python python-3.x python-2.7 raspberry-pi raspbian

当我尝试在python 3中运行该代码时,我发现了Adafruit编写的这段代码(https://drive.google.com/open?id=1TGuTPjfiV4r7ra_5eLMkbXBnesYlvTyT)(并由我进行了修改,以添加一些在python 2.7中可用的额外功能)开发(因为我之前没有看过太多的python 2)它给了我错误:

Traceback (most recent call last):
  File "/home/pi/Forecast-Printer/forecast.py", line 55, in <module>
    printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)
  File "/home/pi/Forecast-Printer/Adafruit_Thermal.py", line 95, in __init__
    self.wake()
  File "/home/pi/Forecast-Printer/Adafruit_Thermal.py", line 605, in wake
    self.writeBytes(255)
  File "/home/pi/Forecast-Printer/Adafruit_Thermal.py", line 189, in writeBytes
    super(Adafruit_Thermal, self).write(chr(arg))
  File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 518, in write
    d = to_bytes(data)
  File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 63, in to_bytes
    raise TypeError('unicode strings are not supported, please encode to bytes: {!r}'.format(seq))
TypeError: unicode strings are not supported, please encode to bytes: 'ÿ'

该代码在运行raspbian(GUI版本)的raspberry pi上运行,并且在通过串行方式与小型热敏打印机通信时,需要与sudo一起运行。

在此先感谢您的帮助:)

编辑: 这是在python 3中运行时触发相同错误的一些代码。

from Adafruit_Thermal import *

printer = Adafruit_Thermal("/dev/serial0", 19200, timeout=5)    

1 个答案:

答案 0 :(得分:0)

从堆栈跟踪中可以看到,当打印机初始化时,Adafruit库通过将整数255串行写入打印机来唤醒打印机。它是通过在第189行上调用Serial类的write()方法(在其自己的write_bytes()方法内部)来实现的:

super(Adafruit_Thermal, self).write(chr(arg))

因为Adafruit_Thermal类继承自Serial,所以可以做到这一点,如您在类定义中所见。

正如@abarnert所指出的那样,chr()返回一个字符串,但是听起来write()在期待二进制数据。因此,我会尝试对您的问题的评论中的两个建议。首先尝试将第189行更改为:

super(Adafruit_Thermal, self).write(arg)

如果这不起作用,请尝试:

super(Adafruit_Thermal, self).write(bytes([arg]))