1
votes

I am trying to read serial port in python in while true loop, I have used try-except condition on KeyboardInterrupt exception. But when I press Ctrl+C nothing happens unless I plug out the device connected to the serial port(getting data from).

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
1

1 Answers

0
votes

Ctrl+C raises KeyboardInterrupt, however you catch this exception and do nothing, so nothing happens. If you would add some logic to your exception block, for example:

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

It would be executed, when you press Ctrl-C. The output of this example after pressing Ctrl-C is:

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

However, I would suggest to use break statement to break out of while loop.

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