-1

How do we return a value from a custom .py tool, so that when I run the tool in another script, it will return a value (such as a number, string, or tuple)?

Notice in the execute class function, I attempt to return a tuple of values (trying both arcpy.SetParameter and return). However, when I run the tool in a separate script, the return value is None.

I use the following code to import the toolbox and run the code:

arcpy.ImportToolbox(pyt_path, "myToolbox")
result = arcpy.myToolbox.HelloWorld()

Below is an example .py script for the tool above

import arcpy

class HelloWorld(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "Hello World"
        self.description = ""
        self.canRunInBackground = False

    def getParameterInfo(self):
        
        """Define parameter definitions"""
        param1 = arcpy.Parameter(
            displayName="output",
            name="outparam",
            datatype="GPString",
            parameterType="Derived",
            direction="Output")

        return [param1]

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def execute(self, parameters, messages):
        """The source code of the tool."""      
        arcpy.AddMessage("Hello World!")
        arcpy.SetParameter(0, "Hello world")
        return "Hello world"

    def postExecute(self, parameters):
        """This method takes place after outputs are processed and
        added to the display."""
        return

Below is my .pyt file

from HelloWorld import HelloWorld

class Toolbox(object):

    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the .pyt file)."""
        self.label = 'Test TBX'
        self.alias = 'TestTBX'

        # List of Tool classes associated with this toolbox
        self.tools = [HelloWorld]

Here is a regular arcpy example using their Spatial Analyst toolbox. I would like to get a return value as well with my custom tool.

# Import system modules
import arcpy
from arcpy import env
from arcpy.sa import Basin

# Set environment settings
env.workspace = "C:/Path/To/Data"

# Set local variables
inFlowDirectionRaster = "flowdir"

# Execute FlowDirection
outBasin = Basin(inFlowDirectionRaster)
8
  • 1
    Read the help file on SetParameter() Commented Mar 21, 2024 at 16:45
  • I tried that option and I could not get it to work. I will edit my code to add that example. Commented Mar 21, 2024 at 16:51
  • Now I see your example code, I repeat read the help file, you are making up syntax that does not exist. Look at the sample code on the help page. Commented Mar 21, 2024 at 17:04
  • I forgot to include the update to the getParameterInfo function. Other than that, I am unsure of how to move forward. Commented Mar 21, 2024 at 17:10
  • I'm not seeing anywhere in your examples where you run the HelloWorld tool? Commented Mar 21, 2024 at 21:57

1 Answer 1

2

Your code worked fine for me returning the text Hello world. My script was:

arcpy.ImportToolbox(r"C:\Temp\ORN\t2.pyt","TestTBX" )
res = arcpy.TestTBX.HelloWorld()
print(res.getOutput(0))

The only things I did was to ensure the HelloWorld.py file was in the same folder as the PYT file and removed the text after the return statement in the execute function; you do not need that as you are passing out the text through the SetParameter(), which you are now correctly defining.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.