PySerial:read() 和 readinto() 有什么区别?
PySerial: What is the difference between read() and readinto()?
我一直在我的代码中使用 pySerial 3.4 从串行端口(准确地说是 RFID 芯片 reader/writer)提取数据。我需要向 reader 发送命令,然后从 reader 读取结果。
基本上,我正在编写一个 12 字节的命令,然后尝试接收 24 字节的输出。
我的问题是:为什么 port.read(24)
不能工作而 res = bytearray(24); port.readinto(res);
工作成功?
附完整代码:
import serial
ser = serial.Serial('COM5',9600,timeout=5,rtscts=True,inter_byte_timeout=5)
def compose_find(port):
port.write(bytes.fromhex('555500000003020405'))
port.flush()
return port.read(12)[6] == 0
def compose_read(port,sec_loc=0,block_loc=0,key='F'*12):
assert sec_loc in range(0,16),'sector location is from 0~15'
assert block_loc in range(0,4),'block location is from 0~3'
assert compose_find(port),'cannot read card!'
sec_loc = '0'+str(hex(sec_loc))[2:]
block_loc = '0'+str(hex(block_loc))[2:]
command = '55 55 00 00 00 0E 03 07 00 00 {} {} 60
{}'.format(sec_loc,block_loc,key).replace(' ','')
parity = str(hex(reduce(lambda x,y:x^y,bytes.fromhex(command))))[2:]
if len(parity) == 1: parity = '0'+parity
command += parity
print(command)
port.write(bytes.fromhex(command))
port.flush()
res = bytearray(24)
port.readinto(res)
return res
compose_read(port=ser,sec_loc=8,block_loc=2)
readinto(buf)
最多读取 len(buf)
字节和 return 秒,而 read(num)
将 阻止 直到 num
字节被接收。你必须在打开端口时指定 timeout
,如果你想要 read()
到 return 即使没有足够的可用数据。
我一直在我的代码中使用 pySerial 3.4 从串行端口(准确地说是 RFID 芯片 reader/writer)提取数据。我需要向 reader 发送命令,然后从 reader 读取结果。
基本上,我正在编写一个 12 字节的命令,然后尝试接收 24 字节的输出。
我的问题是:为什么 port.read(24)
不能工作而 res = bytearray(24); port.readinto(res);
工作成功?
附完整代码:
import serial
ser = serial.Serial('COM5',9600,timeout=5,rtscts=True,inter_byte_timeout=5)
def compose_find(port):
port.write(bytes.fromhex('555500000003020405'))
port.flush()
return port.read(12)[6] == 0
def compose_read(port,sec_loc=0,block_loc=0,key='F'*12):
assert sec_loc in range(0,16),'sector location is from 0~15'
assert block_loc in range(0,4),'block location is from 0~3'
assert compose_find(port),'cannot read card!'
sec_loc = '0'+str(hex(sec_loc))[2:]
block_loc = '0'+str(hex(block_loc))[2:]
command = '55 55 00 00 00 0E 03 07 00 00 {} {} 60
{}'.format(sec_loc,block_loc,key).replace(' ','')
parity = str(hex(reduce(lambda x,y:x^y,bytes.fromhex(command))))[2:]
if len(parity) == 1: parity = '0'+parity
command += parity
print(command)
port.write(bytes.fromhex(command))
port.flush()
res = bytearray(24)
port.readinto(res)
return res
compose_read(port=ser,sec_loc=8,block_loc=2)
readinto(buf)
最多读取 len(buf)
字节和 return 秒,而 read(num)
将 阻止 直到 num
字节被接收。你必须在打开端口时指定 timeout
,如果你想要 read()
到 return 即使没有足够的可用数据。