Encoding error, in python3

笑着哭i 提交于 2019-12-25 16:54:47

问题


I have a somewhat similar question here that I can't solve. In another instance of my code, I face similar encoding errors. Do assist!

My code:

port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=10,     bytesize=8)
f_w = open('/home/ryan/python_serial_output.txt','r+')
f_o = open('/home/ryan/python_serial_parse.txt','w')

port.send_break()
sys_reply = port.read(100000)
sys_reply_str = sys_reply.decode('utf-8')
print(sys_reply_str)
sys_reply_str_haha = sys_reply_str.replace("\r","")
sys_reply_str_haha = sys_reply_str_haha.replace("\n","")
i = list(sys_reply_str_haha)
if str(i[-1]) == '>':
    ip = 'CR1'
    ip_en = ip.encode('utf-8')
    port.write(ip_en)
    read_syscheck = port.read(100000)
    read_syscheck_str = read_syscheck.decode('utf-8')
    print(read_syscheck_str)

Yes, it's inefficient, but I'm writing it step by step to avoid errors as a start.

With this code, this is the result I get.

myname@Toshiba:~$ python3 serial_test.py 

Explorer (c) 2009
All rights reserved.
Firmware Version: 34.11  

>
Traceback (most recent call last):
  File "serial_test.py", line 25, in <module>
    read_syscheck_str = read_syscheck.decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd3 in position 7: invalid continuation byte

It seems I am encoding 'CR1' wrongly, that's why the error has been prompted. CR1 is supposed to reset my sensor to factory default settings, and meant to reply a confirmation of that.

Thank you very much in advance for any assistance.


回答1:


Wrong encoding method.

Correct one was 'cp437'

Unsure why UTF-8 worked after the break, but not after writing a command



来源:https://stackoverflow.com/questions/44194539/encoding-error-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!