Select to view content in your preferred language

Python scripts - Print statements and arcpy.AddMessage

24587
5
Jump to solution
07-09-2014 11:57 AM
DarrenMcCormick
Emerging Contributor

Hi:

Through Pythonwin I have created a collection of scripts that I have incorporated into an ArcToolbox. I have shared this toolbox with several colleagues and clients. When developing scripts I use print statements to track the progression of test runs. After I have finished developing my scripts they are typically run through ArcToolbox; however, when there are occasions when I have to run a script repeatedly to process data for several large extents I will setup a batch file so processing can run through unattended.

My question:

Use of print statements will write messages to the screen when running a script through an IDE. Use of arcpy.AddMessage will write messages to the screen when running a script through an ArcToolbox script tool. What is the best way to setup a Python script to write messages to the screen whether the script is being run through an IDE or ArcToolbox? Is there code that can identify where the script is running from (i.e. through either an IDE or through a script tool in ArcToolbox) and write messages to the screen using print statements or arcpy.AddMessage, whichever is appropriate?

Thanks in advance for any comments/feedback!

0 Kudos
1 Solution
5 Replies
IanGrasshoff
Regular Contributor

I don't know of any modules/classes to identify if the script is running from ArcGIS toolbox vs. Python IDE.  However, I have also run into this very thing.  Here is my solution.

I have a simple function I wrote to handle this type of thing.

# Function to write info to log file

# passing a value of 1 along with the msg will log in info to a file, otherwise the function will just a print a message

def loginfo(msg, loglevel):

    if loglevel == 1:

        log = open(logfile,'a')

        log.write('\n---------')

        log.write(msg)

        log.close()

        print msg

        arcpy.AddMessage(msg)

    else:

        print msg

        arcpy.AddMessage(msg)

    return

It's pretty simple function that takes a message string and an integer.  It's pretty standard in all my scripts (I should create it as a module/class so I can import it).  If you want to use it make sure to create a logfile variable with a path to a file to log to.

0 Kudos
JamesCrandall
MVP Frequent Contributor

Print statements will display in ArcMap's Python window for Add-In tools.  Not sure if that helps.

0 Kudos
DarrenMcCormick
Emerging Contributor

Thanks to Dan, Ian, and James who have each experienced this issue and have proposed workable solutions. I find myself in a difficult position in having to select which is the "Correct Answer".

-Darren

0 Kudos
DanPatterson_Retired
MVP Emeritus

The question remains open and assumed answered and it appears that there were no useful suggestions