Break Handler

Trap keyboard interrupts.

Taken from the internet: https://stacyprowell.com/blog/2009/03/trapping-ctrlc-in-python/

Comments are the original author’s.

class break_handler.BreakHandler(emphatic=9)[source]

Trap CTRL-C, set a flag, and keep going. This is very useful for gracefully exiting database loops while simulating transactions.

To use this, make an instance and then enable it. You can check whether a break was trapped using the trapped property:

# Create and enable a break handler.
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...
count

The number of breaks trapped.

disable()[source]

Disable trapping the break. You can check whether a break was trapped using the count and trapped properties.

enable()[source]

Enable trapping of the break. This action also resets the handler count and trapped properties.

trapped

Whether a break was trapped.