编码错误,在python3中 [英] Encoding error, in python3

查看:134
本文介绍了编码错误,在python3中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的问题

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!

我的代码:

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

似乎我在错误地编码"CR1",这就是提示错误的原因. CR1应该将我的传感器重置为出厂默认设置,并希望对此进行回复.

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.

非常感谢您的协助.

推荐答案

错误的编码方法.

正确的是'cp437'

Correct one was 'cp437'

不确定为什么UTF-8在中断后起作用,但在编写命令后却不能起作用

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

这篇关于编码错误,在python3中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆