Select to view content in your preferred language

Calling one arcscript from another - proper method?

1631
1
Jump to solution
03-14-2011 05:35 AM
StevePeaslee
Deactivated User
My question is similar to the one Esther posted  last week. I haven't been able to find good documentation on the proper method for executing one ArcScript Tool (with loop) that calls a second ArcTool. The second script must also be able to run as a standalone ArcScript.

I tried to search for the proper way to design a script with functions or methods. I have a feeling that I'm missing something in the basic design and how my second script initiates.

Below are examples of two simple scripts designed to be run as ArcTools. I've also attached the two scripts. The first contains the loop, list all tables in the input workspace. The second script (which also needs to be able to run standalone) lists all fields in the input table. Can anyone point out the proper method for setting up the modules and importing the second script?

"
# list_all_tables.py
#
# test script - calls list_all_fields.py
#
## =========================================================================
def AddMsgAndPrint(msg, severity=0):
    # prints message to screen if run as a python script
    # Adds tool message to the geoprocessor
    print msg
    #
    # Split the message on \n first, so that if it's multiple lines, a GPMessage will be added for each line
    try:
        for string in msg.split('\n'):
            #Add a geoprocessing message (in case this is run as a tool)
            if severity == 0:
                gp.AddMessage(string)
               
            elif severity == 1:
                gp.AddWarning(string)
               
            elif severity == 2:
                gp.AddMessage("    ")
                gp.AddError(string)
               
    except:
        pass

## ========================================================================
def errorMsg():
    try:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        theMsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value)
        AddMsgAndPrint(theMsg, 2)

    except:
        AddMsgAndPrint("Unhandled error in errorMsg method", 2)
        pass

## ======================================================================
## MAIN
## =========================================================================
# Import system modules
import os, sys, traceback, arcgisscripting

# Create geoprocessing object
gp = arcgisscripting.create(9.3)

try:
    AddMsgAndPrint("\nRunning list_all_tables.py", 1)

    # Single input parameter - input workspace
    wksp = gp.GetParameterAsText(0)
    gp.Workspace = wksp

    # import the second ArcScript
    # This import is causing the second script to execute, using the
    # input parameter from THIS script and causing an error.
    import list_all_fields

    # create list of tables in workspace
    tables = gp.ListTables()

    for theTable in tables:
        # call second script to list the fields for this table
        # this SEEMS to work OK
        AddMsgAndPrint("\nPrinting fields for " + theTable, 1)
        bListed = list_all_fields.printFields(theTable)

    AddMsgAndPrint("\nlist_tables finished\n", 1)
   
except:
    AddMsgAndPrint("\nError in list_all_tables.py", 0)
    errorMsg()


# list_all_fields.py
#
# Test script called by list_all_tables.py
#
# Single input parameter: a table

## =========================================================================
def AddMsgAndPrint(msg, severity=0):
    # prints message to screen if run as a python script
    # Adds tool message to the geoprocessor
    print msg
    #
    # Split the message on \n first, so that if it's multiple lines, a GPMessage will be added for each line
    try:
        for string in msg.split('\n'):
            #Add a geoprocessing message (in case this is run as a tool)
            if severity == 0:
                gp.AddMessage(string)
               
            elif severity == 1:
                gp.AddWarning(string)
               
            elif severity == 2:
                gp.AddMessage("    ")
                gp.AddError(string)
               
    except:
        pass

## =======================================================================
def errorMsg():
    try:
        tb = sys.exc_info()[2]
        tbinfo = traceback.format_tb(tb)[0]
        theMsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value)
        AddMsgAndPrint(theMsg, 2)

    except:
        AddMsgAndPrint("Unhandled error in errorMsg method", 2)
        pass
   
## ========================================================================
def printFields(theTable):
    # This function does all the work
    #
    try:
       
        fields = gp.ListFields(theTable)
        iCnt = 1
      
        for field in fields:
            AddMsgAndPrint("\t" + str(iCnt) + ". " + field.Name, 1)
            iCnt += 1
                         
        return True
   
    except:
        errorMsg()
        return False
               
## ======================================================================= 
## ====================================================================       
# Import system modules
import os, sys, traceback, arcgisscripting

# Create geoprocessing object
gp = arcgisscripting.create(9.3)

try:
    # single input parameter - a table
    theTable = gp.GetParameterAsText(0)
   
    theScript = os.path.basename(sys.argv[0])

    if theTable:
        AddMsgAndPrint("\nPrinting list of fields for " + theTable, 1)
       
    if printFields(theTable):
        AddMsgAndPrint("\n" + theScript + " successful\n", 1)

except:
    AddMsgAndPrint("\nError in " + theScript, 0)
    errorMsg()

"
0 Kudos
1 Solution

Accepted Solutions
by Anonymous User
Not applicable
Original User: clm42

Well there is the esri toolbox way and the python way. The esri way is to add the script to a toolbox and then reference the tool in the second script the way you call any tool. The python way is to use subprocess to just launch the .py straight in your os. If option 1 is giving you problems move to option 2 and never look back. subprocess.Popen() will launch anything you want. This is an example from a script of mine that launches a PDF that is exported during the script run. It tells your os "hey open this file with this program."

subprocess.Popen([r'C:\Program Files\Adobe\Acrobat 9.0\Acrobat\Acrobat.exe',r'C:\GIS Projects\TaxChange\Export\%s%s20%s taxable.pdf'% (max(datelist)[4:6],max(datelist)[6:8],max(datelist)[2:4])])

View solution in original post

0 Kudos
1 Reply
by Anonymous User
Not applicable
Original User: clm42

Well there is the esri toolbox way and the python way. The esri way is to add the script to a toolbox and then reference the tool in the second script the way you call any tool. The python way is to use subprocess to just launch the .py straight in your os. If option 1 is giving you problems move to option 2 and never look back. subprocess.Popen() will launch anything you want. This is an example from a script of mine that launches a PDF that is exported during the script run. It tells your os "hey open this file with this program."

subprocess.Popen([r'C:\Program Files\Adobe\Acrobat 9.0\Acrobat\Acrobat.exe',r'C:\GIS Projects\TaxChange\Export\%s%s20%s taxable.pdf'% (max(datelist)[4:6],max(datelist)[6:8],max(datelist)[2:4])])
0 Kudos