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()
3
  • 2
    Why would a try / except KeyboardInterrupt affect the rest of your code? Commented Nov 22, 2018 at 10:15
  • Old related: stackoverflow.com/questions/1335507/… Commented Nov 22, 2018 at 10:16
  • You could create a second thread that changes a variable value on keyboardinput. And let the main thread run the while loop while variable True. Commented Nov 22, 2018 at 10:24

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I did this but instead of this, i would like assign a key for break. not ctrl+c

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.