在 Ubuntu 上的 Python 3 上字节到字符串的错误编码 [英] Erratic encoding of byte to string on Python 3 on Ubuntu

查看:44
本文介绍了在 Ubuntu 上的 Python 3 上字节到字符串的错误编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,正在研究传感器.我正在逐行构建我的代码,但我在字节到字符串的编码/解码部分遇到了麻烦.相同的代码,有时有效,有时无效.

I'm new to Python and am working on a sensor. I'm building my code line by line and I have trouble with the encoding/decoding part for bytes to string. Same code, sometime it works, sometime it dosen't.

代码如下:

import serial
import time
import os

port = serial.Serial("/dev/ttyUSB0", baudrate=9600, timeout=1,      bytesize=8)
f_w = open('/home/myname/python_serial_output.txt','r+')

port.send_break()

while True:
    op = port.read(2)
    op_str = op.decode('utf-8')
    f_w.write(op_str)
    print(op_str)

第一次没有成功,但第二次成功了.为什么?

It didn't work the first time round, but worked on the second time. Why?

这是我得到的错误:

myname@Toshiba:~$ python3 serial_test.py 
Traceback (most recent call last):
  File "serial_test.py", line 13, in <module>
    op_str = op.decode('utf-8') 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 0: invalid start byte

myname@Toshiba:~$ python3 serial_test.py 
Ex
pl
or
er

如何消除它运行成功的歧义?

How do I remove the ambiguity of it running successfully?

推荐答案

这可能是因为您的字符串包含非 ascii 字符.当您再次运行代码时,字符串中没有非 ascii 字符,因此运行成功.

This may have have happened because your string had a non ascii character. When you ran your code again there was no non ascii character in the string and hence it ran successfully.

您可以使用 encode() 函数对非 ascii 字符进行编码

You can encode the non ascii characters by using encode() function

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

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