【问题标题】:Data received through serial in Python在 Python 中通过串行接收的数据
【发布时间】:2015-03-10 12:47:08
【问题描述】:

我已经在 Raspberry Pi UART 上进行了配置,这是我的串行读/写代码:

ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1)
ser.open()
string = '#SET0\r\n'
print string
ser.write(string)
bytes2read = ser.inWaiting()
print bytes2read
if (ser.inWaiting()>0):
  incoming = ser.readline()
  print incoming
time.sleep(5)
bytes2read1= ser.inWaiting()
print bytes2read1
if (ser.inWaiting()>0):
  print "Data:"
  cont = ser.read(bytesaleer1)
print cont

cont 格式如下:

#D0:0:0:10
#D1:0:0:56
#D2:0:0:23
#D3:1:1:90
--------

我的问题是,如何获取并保存该变量的最后一个 0?我想保存从 cont 获得的 c0,c1,c2,c3 值; 10、56、23 和 90。 已尝试使用 line.strip,但效果不佳。

【问题讨论】:

  • int(cont.split(':')[-1])
  • int(cont.split(':')[-1]) ValueError: int() 基数为 10 的无效文字:'0\r\n--------\ r\n'
  • 然后int(cont.split(':')[-1].rstrip('\r\n-'))
  • 伙计们,先阅读问题。 cont.split(':')[-1] 如何从不同的行产生四个值?

标签: python split text-processing strip


【解决方案1】:

如果cont 是一个包含所有五行文本的字符串,包括-------- 分隔线,我会先将它分成几行:

cont.splitlines()
    => [ '#D0:0:0:10',
         '#D1:0:0:56',
         '#D2:0:0:23',
         '#D3:1:1:90',
         '--------' ]

然后你可以遍历所有的行,并且如果该行包含一个冒号,拉出最后一个值并保存它。

vals = []
for line in cont.splitlines():
    if ':' in line:
        v = int(line.split(':')[-1])
        vals.append(v)

>>> vals
[10, 56, 23, 90]

【讨论】:

  • 用你的代码 Tim Pierce 工作就像一个魅力,真的很感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 2018-03-14
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
相关资源
最近更新 更多