【问题标题】:How do i parse live csv data from a serial port in Python?如何从 Python 中的串口解析实时 csv 数据?
【发布时间】:2019-04-20 03:51:12
【问题描述】:

我是 python 的新手,我正在尝试创建一个程序,该程序从 COM 端口(连接到风检测器)获取实时输入并将实时数据解析为更人性化的输出。当前从端口接收到的数据是csv格式的:

Q,060,000.10,M,00,19

“Q”为当前节点地址,

“060”是风向,

“000.10”是风速,

“M”为单位(m/s),

“00”是状态,最后一个数字是校验和。

我能够让 python 通过 Pyserial readline() 打印出连续数据,但是它是默认格式,这不是我想要的。我尝试使用 csv.reader 来解析和读取代码,但是我似乎无法以正确的格式打印它。我尝试在其中实现 csv.reader,但结果将每个项目分隔为一个新行。

这是我用于读取和解析的代码。

while True:
    data = ser.readline().decode('ascii')
    csvReader = csv.reader(data, delimiter=',')
    for row in csvReader:
        print(row)

我现在得到的结果是:

['\x02']
['Q']
['', '']
['', '']
['0']
['0']
['0']
['.']
['0']
['1']
['', '']
['M']
['', '']
['0']
['0']

我正在尝试获得类似于此的最终输出:

"Wind Direction is 60deg. 
Wind Speed is 0.10 m/s. 
The current status is Ok"

【问题讨论】:

  • 看起来readline() 不起作用。如果您删除最后三行代码并改为:print('>>{}<<'.format(data)),它会是什么样子?

标签: python csv parsing pyserial


【解决方案1】:

你可以试试这个:

while True:
    data = ser.readline().decode('ascii')
    # print(data)  # uncomment this line to debug the coming data
    node, direction, speed, M, status = data.split(',')

    print(f"Wind Direction is {direction} deg.") 
    print(f"Wind Speed is {speed} m/s.") 

【讨论】:

    猜你喜欢
    • 2013-04-12
    • 2023-04-03
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 2021-03-30
    • 1970-01-01
    • 2021-01-08
    相关资源
    最近更新 更多