writing arcpy.GetMessages() to a text file?

1553
7
07-05-2018 02:50 PM
KeithD1
New Contributor III

Is there anything wrong with this very simplistic way of writing geo-processing messages to a plain text file? Being new to Python, I was surprised it was this easy....I must be overlooking something!

To clarify, I am intending to write the messages from the last tool which was invoked in the script.

f = open(resultLogFile, "a")

s = str(arcpy.GetMessages())
f.write(s)

0 Kudos
7 Replies
DanPatterson_Retired
MVP Esteemed Contributor

It works... use it... if there was more than 1 message you could get fancy with string formatting

#s = str(arcpy.GetMessages())

messages = [1, 'two', 'three']  # a substitute for your s... no need to convert to str

s = ("Script messages returned...\n" + "\n{}"*len(messages)).format(*messages)

print(s)

# print or save... this is the return

Script messages returned...

1
two
three
KeithD1
New Contributor III

Thanks Dan. I do have multiple messages (potentially hundreds)....but my three lines of code seems to handle this. Every message ends up on its own line in the text file.

So you know how much of a noob I am at Python....I'm not even sure what you're doing with the curly-brackets or asterisk. Will do some edumacating and see what that's about. Thanks!

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor
JoshuaBixby
MVP Esteemed Contributor

A slightly more compact, and more Pythonic way, would be to use a Python with statement:

with open(resultLogFile, "a") as f:
    f.write(arcpy.GetMessages())
JoeBorgione
MVP Esteemed Contributor

I like that... a lot!

That should just about do it....
0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

although starred expressions and assignment expressions are as simple as you can get

https://docs.python.org/3/reference/simple_stmts.html#expression-statements

0 Kudos
by Anonymous User
Not applicable

 

How do you script out the location of the txt file / is there more to the script than what has been shared on this thread.

I am wanting to extract the Message from geocoding results and log them in a txt file with the corresponding txt file that is created when you "Save A Python Script", since doing that does not bring along the messages.

In this thread it is said to manually copy and paste the messages to a txt file directly from the GP History log pane in Pro

 

https://community.esri.com/t5/modelbuilder-questions/model-builder-can-i-write-text-from-results-win...

 

Capture.JPG

It would be nice to be able to run weekly geocoder rebuilds and geocode our address data against our actual and theoretical address ranges along with a fishbone analysis to track and log the progress and accuracy of our address data, especially since this data is shared with our communications people.

 

 
0 Kudos