开发者

Infinity Loop and user input as the termination

开发者 https://www.devze.com 2023-01-11 04:43 出处:网络
I have my code and it does go run to infinity. What I want is that if on开发者_开发技巧 the unix command window if the user inputs a ctrl C, I want the program to finish the current loop it in and the

I have my code and it does go run to infinity. What I want is that if on开发者_开发技巧 the unix command window if the user inputs a ctrl C, I want the program to finish the current loop it in and then come out of the loop. So I want it to break, but I want it to finish the current loop. Is using ctrl C ok? Should I look to a different input?


To do this correctly and exactly as you want it is a bit complicated.

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

Edit: Based on your comment below, a typical usage of the class BreakHandler is:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消