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()
if ih.trapped:
break
ih.disable()
source
share