Python toolboxes should not be considered isolated from your data management and analysis workflow. Many of us have a desire to use the functionality in our python toolboxes in conjunction with our other arcpy code. You could build an easy to import companion .py file to hold your toolbox business logic next to your actual toolbox (ie. myTbx.pyt and myTbxFunctions.py), however, pyt files can be accessed and used in your interpreter or IDE by using imp. The example below shows this with our metadataUpdateItems tool. There are a couple important things to note if using pyt outside of ArcCatalog:
- python toolbox parameters have a valueAsText attribute that is set when running via ArcCatalog and will not be created when building the arcpy.parameter object in this manner.
- The alternative to valueAsText is to interpret the .value attribute as a string where needed
- Additional arcpy.parameter attributes are updated in ArcCatalog including, but not limited to, param.altered or param.hasBeenValidated, in the case below we added a variable to bypass those checks when not using in arcCatalog
import imp
def getParamByName(params, name):
outParam = None
for param in params:
if param.name == name:
outParam = param
#import toolbox
myTbx = imp.load_source('t',r'C:\dsCode\toolboxes\myTbx.pyt')
#build the toolbox parameter objects list
params = myTbx.metadataUpdateItems().getParameterInfo()
#retrieve the parameter to update and change its value
inLyr = getParamByName(params, 'inLyr')
inLyr.value = 'C:\\temp\mySDElyr'
#update the parameters
#Note: the second argument is a runAsFunction binary T/F
# this is to bypass the parameter.altered or parameter.validated checks of the updateParameters code
myTbx.metadataUpdateItems().updateParameters(params,True)
#update a list parameter
agolTags = getParamByName(params, 'agolTags')
agolTags.values = [u'wildlife (open data)']
#execute the toolbox
myTbx.metadataUpdateItems().execute(params, None)