Canceling a Python script in Rhino

In Rhino 6, when a script is running and it is not waiting for user input, it can be cancelled by pressing the ESC. In Rhino.Python this is done by adding a scriptcontext.escape_test test.

The following script is not be cancelled by pressing the ESC key.

def TightLoopEscapeTest():
  for i in range(10000):

TightLoopEscapeTest()

By scriptcontext.escape_test function the loop can now be canceled:

import scriptcontext

def TimeConsumingTask():    
    for i in range(10000):
        # Was escape key pressed?
        if (scriptcontext.escape_test(False)):
            print "TimeConsumingTask cancelled."
            break
        print i

TimeConsumingTask()

It might be necessary to press the ESC key a couple times to catch the scriptcontext.escape_test test in the correct state.