如何在python中把3个连接字符串改为字节?

问题描述 投票:0回答:1

当我在python 3中运行以下代码时,出现了一个错误,我找遍了所有的地方,但都没有找到正确的方法,希望得到帮助。

raise TypeError('unicode strings are not supported, please encode to bytes: r}'.format(seq))TypeError: unicode strings are not supported, please encode to bytes: 'relay read 7\nr'.

我需要通过串口发送以下字符串:中继读取#of中继。

import sys
import serial

if (len(sys.argv) < 2):
    print ("Usage: relayread.py <PORT> <RELAYNUM>\nEg: relayread.py COM1 0")
    sys.exit(0)
else:
    portName = sys.argv[1];
    relayNum = sys.argv[2];

#Open port for communication    
serPort = serial.Serial(portName, 19200, timeout=1)

if (int(relayNum) < 10):
    relayIndex = str(relayNum)
else:
    relayIndex = chr(55 + int(relayNum))

serPort.write("relay read "+ relayIndex + "\n\r")

response = serPort.read(25)

if(response.find("on") > 0):
    print ("Relay " + str(relayNum) +" is ON")

elif(response.find("off") > 0):
    print ("Relay " + str(relayNum) +" is OFF")

#Close the port
serPort.close()
serial-port pyserial
1个回答
0
投票

使用字符串的 encode 方法来构造相应的字节序列。

在这种情况下,字符串中的所有字符都在ASCII范围内,所以使用哪种编码方案并不重要。 (编码方案之间的差异通常只在处理非 ASCII 字符时才有意义,这些字符的 ord() 值大于127)。 所以在这种情况下,你甚至不需要指定一个特定的编码方案,你可以简单地使用 encode 方法,并且不使用参数,让 Python 应用平台的默认编码。

要做到这一点,请将这个。

serPort.write("relay read "+ relayIndex + "\n\r")

改为 this。

serPort.write(("relay read "+ relayIndex + "\n\r").encode())

你可能需要做反向操作,从由 serPort.read. 改成:

response = serPort.read(25)

改为:

response = serPort.read(25).decode()

另外,在传输的数据中,一般来说,行结束是用回车和换行来表示的,或者是 "\r\n". 在你的 serPort.write 呼叫,你用的是反。"\n\r". 这是不寻常的,但如果这是你的设备需要,那么就这样吧。

© www.soinside.com 2019 - 2024. All rights reserved.