2017-05-25 98 views
0

我是Python新手,正在研究傳感器。 我正在逐行構建我的代碼,並且我在字符串的字節編碼/解碼部分遇到問題。相同的代碼,有時它可以工作,有時候它不會。Ubuntu上Python 3字節到字符串的不規則編碼

下面是代碼:

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) 

它沒有工作的第一次全面,但在第二次合作。爲什麼?

以下是錯誤我得到:

[email protected]:~$ 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 

[email protected]:~$ python3 serial_test.py 
Ex 
pl 
or 
er 

如何刪除成功運行了它的不確定性?

回答

0

這可能是因爲你的字符串沒有ascii字符而發生的。當您再次運行代碼時,字符串中沒有非ascii字符,因此它已成功運行。

您可以使用編碼()函數編碼非ascii字符

+0

因此,我應該編碼我的整個操作之前解碼它? –