【问题标题】:How to break while loop when reading a serial port in python在python中读取串口时如何打破while循环
【发布时间】:2019-04-20 14:27:32
【问题描述】:

我试图在 while true 循环中读取 python 中的串行端口,我在 KeyboardInterrupt 异常上使用了 try-except 条件。但是当我按下 Ctrl+C 时,除非我拔出连接到串行端口的设备(从中获取数据),否则什么都不会发生。

try:
    while True:
        x = ser.readline()
        dat=x.decode('utf8').split(",")
        dat[0]=dat[0].replace("\x00","")
        if(dat[0][0:2]=='ax' and dat[1][0:2]=='gx'):
            ax=dat[0][2:]
            gx=dat[1][2:]
            flagx=1
        if(dat[0][0:2]=='ay' and dat[1][0:2]=='gy' and flagx==1):
            ay=dat[0][2:]
            gy=dat[1][2:]
            flagx=2
        if(dat[0][0:2]=='az' and dat[1][0:2]=='gz' and flagx==2):
            az=dat[0][2:]
            gz=dat[1][2:]
            flagx=0
            dgx.append(gx)
            dgy.append(gy)
            dgz.append(gz)
            dax.append(ax)
            day.append(ay)
            daz.append(az)
         print(dat)
except KeyboardInterrupt:
    pass

【问题讨论】:

    标签: python pyserial try-except


    【解决方案1】:

    Ctrl+C 引发KeyboardInterrupt,但是你捕捉到这个异常并且什么都不做,所以什么也没有发生。如果您要在异常块中添加一些逻辑,例如:

    while True: 
        try: 
            pass 
        except KeyboardInterrupt: 
            print('Hello world!') 
            raise 
    

    当你按下 Ctrl-C 时它会被执行。这个例子在按下 Ctrl-C 后的输出是:

    ^CHello world!
    ---------------------------------------------------------------------------
    KeyboardInterrupt                         Traceback (most recent call last)
    

    但是,我建议使用break 语句来打破while 循环。

    while True:
        x = ser.readline()
        if x == termiation_line:
            break
    

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 2012-12-07
      • 2021-07-02
      • 2016-10-09
      • 1970-01-01
      • 2012-04-03
      相关资源
      最近更新 更多