What is the best way to implement an infinite loop in Python, such that a given function is run again and again until the user presses a key? I can think of a couple of ways of doing this, one of which involves Ctrl-C, and the other involves threading: both of which seem extremely hacky, and leave me with the feeling that I'm missing something blindingly obvious.
Here's a minimal working example of the Ctrl-C method:
def run():
my_object = MyClass()
my_object.lay_the_table()
print("Telling my_object to keep refreshing... Use Ctrl-C to stop.")
while True:
my_object.refresh()
my_object.tidy_away()
if __name__ == "__main__":
run()
The failings of this method are obviously:
- The
tidy_away()
method is never called. - I can't imagine it's ever good practice to invite the user to kill the program manually.
But what's a better way?
I'm really surprised that I can't find a similar question to this one - for Python - on Stack Overflow. Then again, it might well be that I'm just not using the search function properly! Happy to have this question marked as a duplicate if it points me to a solution.