ArcPy includes a GetMessages()
function that you can use to retrieve messages generated when an ArcGIS tool is executing. Messages can include informational messages, such as the start and ends times of a tool execution as well as warnings and errors, which can result in something less than the desired result or complete failure of the tool to execute to completion.
During the execution of a tool, various messages are generated. These messages include informational messages, such as the start and end times of a tool execution, parameter values passed to the tool, and progress information. In addition to this, warnings and errors can also be generated by the tool. These messages can be read by your Python script, and your code can be designed to appropriately handle any warnings or errors that have been generated.
ArcPy stores the messages from the last tool that was executed and you can retrieve these messages using the GetMessages()
function, which returns a single string containing all messages from the tool that was last executed. You can filter this string in terms of severity to return only certain types of messages such as warnings or errors. The first message will always include the name of the tool executed, and the last message is the start and end time.
In this recipe, you will add a line of code to the except
statement, which will print more descriptive information about the current tool run.
Follow these steps to learn how to add a GetMessages()
function to your script that generates a list of messages from the tool that was last executed:
C:ArcpyBookCh11ErrorHandling.py
file in IDLE.GetMessages()
function:import arcpy try: arcpy.env.workspace = "c:/ArcpyBook/data" arcpy.Buffer_analysis("Streams.shp","Streams_Buff.shp") except: print(arcpy.GetMessages())
C:ArcpyBookcodeCh11ErrorHandling3.py
solution file.Executing: Buffer c:/ArcpyBook/dataStreams.shp c:/ArcpyBook/dataStreams_Buff.shp # FULL ROUND NONE # Start Time: Tue Nov 13 22:23:04 2012 Failed to execute. Parameters are not valid. ERROR 000735: Distance [value or field]: Value is required Failed to execute (Buffer). Failed at Tue Nov 13 22:23:04 2012 (Elapsed Time: 0.00 seconds)
The GetMessages()
function returns all the messages generated by the last tool that was run. I want to emphasize that it only returns messages from the last tool that was run. Keep this in mind if you have a script with multiple tools that are being run. Historical tool messages are not accessible through this function. However, there is a Result
object that you can use if you need to retrieve historical tool messages.