0

Simplified version of code is below. In the while loop I normally process data from serial port and measurement is not limited by time or any value. I want to stop execution with key anytime i need to stop.

try-except is easiest way but it will affect also main code it is implemented. It is not good option in my case. I couldn't find how to fit keyboard monitoring here enter link description hereinto class and also same for signals. I would like to insert an if-statement which calls other function in class to stop execution of loop. Any help would appreciated. Thanks

import time

class Something:

    def __init__(self):
        self.looping()

    def looping(self):
        i=0
        while True:
            i+=1
            time.sleep(1)
            print(i)

some=Something()
roganjosh
  • 12,594
  • 4
  • 29
  • 46
Carmelo
  • 9
  • 1
  • 3

1 Answers1

1
import time
class Something:
    def __init__(self):
        self.looping()

    def looping(self):
        i=0

        while True:
            try:
                i+=1
                time.sleep(1)
                print(i)
            except KeyboardInterrupt:
                break
some=Something()
Srce Cde
  • 1,764
  • 10
  • 15