Erratic encoding of byte to string on Python 3 on Ubuntu

时间秒杀一切 提交于 2019-12-20 05:45:08

问题


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.

Here is the code:

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?

Here is the error I get:

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?


回答1:


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.

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



来源:https://stackoverflow.com/questions/44175928/erratic-encoding-of-byte-to-string-on-python-3-on-ubuntu

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