Endless loop and user input as completion

I have a code and it runs endlessly. I want that if in the unix command window, if the user enters ctrl C, I want the program to end the current loop and then exit the loop. So I want it to break, but I want it to complete the current loop. Uses ctrl C ok? Should I look for another input?

+3
source share
1 answer

To do it right and exactly as you want, is a little complicated.

Basically you want to catch Ctrl-C, set a flag, and continue until the start of the loop (or end) where you check for this flag. This can be done using the module signal. Fortunately, someone has already done this, and you can use the code in the linked example .

Change . Based on your comment below, typical use of the class BreakHandler:

ih = BreakHandler()
ih.enable()
for x in big_set:
    complex_operation_1()
    complex_operation_2()
    complex_operation_3()
    # Check whether there was a break.
    if ih.trapped:
        # Stop the loop.
        break
ih.disable()
# Back to usual operation
+3
source

Source: https://habr.com/ru/post/1759023/


All Articles