python capture the Cancel button and terminate gracefully

870
2
11-02-2018 05:19 PM
GeorgeRiner
New Contributor III

Seems a simple question: My python tool is looping through records and outputting a "<current record> being processed" message in the tool's running dialog box. As the tool loops through the <records> it's generating some output file (in this case an excel file). I'm using the SetProgressor/SetProgressorPosition feature of arcpy to show progress through the loop.  But now my users understandably want to be able to click on the 'Cancel' button in the upper right corner of the dialog box and have the tool stop running, but still save the results of the <records> that were processed.

This site (arcpy - Forcing Python Toolbox tool to break loop and do cleanup when user clicks Cancel? - Geograph... ) claims that you can wrap the arcpy.SetProgressorPosition() call in a try/except construct and that the except clause gets executed if the user has clicked on the Cancel button.  (I'm running ArcGIS Desktop 10.4.1 in Windows 10)

I do not finding the above technique to work.

How does an arcpy script capture the user clicking on 'Cancel' and having a chance to clean-up before exiting?

0 Kudos
2 Replies
JoshuaBixby
MVP Esteemed Contributor

Sharing with Python‌ since this is ArcPy related and not ArcGIS API for Python.

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

The StackExchange reply was based on someone using 10.3.1, before arcpy.env.autoCancelling was introduced.  Have you tried reading and implementing Understanding cancellation behavior in script tools—Help | ArcGIS Desktop