问题
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