使用 Python 解析从 USB 读取的串行数据
Parsing serial data read in from USB using Python
我对 python 完全陌生。
我正在使用以下代码从 USB 设备提取数据,该设备使用 printf() 将数据打印到我的 raspberry Pi。我正在使用以下 python 代码读取此数据并将其打印到屏幕:
#!/usr/bin/python
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',\
baudrate=115200,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
ser.write("help\n");
while True:
line = ser.readline();
if line:
print(line),
ser.close()
代码按预期打印了以下结果(这就是我使用 printf() 的目的):
Received Ticks are: 380 and nodeID is: 1
我如何解析行变量,以便我可以将 Ticks (380) 和 nodeID (1) 的数量保存到两个变量中,以便我可以将这些变量用于 HTTP POST 请求python?
拆分字符串,然后取你想要的部分:
>>> s = "Received Ticks are: 380 and nodeID is: 1"
>>> s.split()
['Received', 'Ticks', 'are:', '380', 'and', 'nodeID', 'is:', '1']
>>> words = s.split()
>>> words[3]
'380'
>>> words[7]
'1'
>>>
我对 python 完全陌生。
我正在使用以下代码从 USB 设备提取数据,该设备使用 printf() 将数据打印到我的 raspberry Pi。我正在使用以下 python 代码读取此数据并将其打印到屏幕:
#!/usr/bin/python
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',\
baudrate=115200,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
ser.write("help\n");
while True:
line = ser.readline();
if line:
print(line),
ser.close()
代码按预期打印了以下结果(这就是我使用 printf() 的目的):
Received Ticks are: 380 and nodeID is: 1
我如何解析行变量,以便我可以将 Ticks (380) 和 nodeID (1) 的数量保存到两个变量中,以便我可以将这些变量用于 HTTP POST 请求python?
拆分字符串,然后取你想要的部分:
>>> s = "Received Ticks are: 380 and nodeID is: 1"
>>> s.split()
['Received', 'Ticks', 'are:', '380', 'and', 'nodeID', 'is:', '1']
>>> words = s.split()
>>> words[3]
'380'
>>> words[7]
'1'
>>>