7

in a script within a toolbox I'm trying to call a model in that same toolbox. Currently I have to hardwire the path.

arcpy.ImportToolbox(r"[PATH]", "LLPGToolbox")
arcpy.llpg_LLPGToolbox(inputFolder, output15, output21, output24, processedLLPG)

Is there a way of doing this without the need to hardwire paths each time (i.e. 'look in the toolbox I'm in for script X').

4

This is how I currently do it:

import arcpy

tbx_path = r'C:\ArcGIS\Toolbox.tbx'
tbx_alias = 'MyCustomToolbox'
tbx = arcpy.ImportToolbox(tbx_path,tbx_alias)
tbx
>>> <module 'MyCustomToolbox' (built-in)>

Then I run

custom_model = getattr(arcpy,'{0}_{1}'.format('Model',tbx_alias))

which is essentially building a string that I can put after arcpy.:

'arcpy.Model_MyCustomToolbox'

Now I can use custom_model() as a regular Python function (with input args etc).

6

ArcGIS has to be able to find the Toolbox, but that doesn't mean you have to specify the path each time.

The easiest way may be to just ensure that the toolboxes are in the same folder, and then just use the file name, for example:

arcpy.ImportToolbox('Toolbox.tbx,'toolboxalias')

If you are running the PythonToolbox tool from within ArcGIS, the directory that contains that toolbox is added to the path (look at the value of sys.path).
When you use arcpy.ImportToolbox without a full path, ArcGIS will check all of the directories listed in sys.path and then it also checks arcpy.env.workspace.

If locating the toolboxes in the same folder isn't possible, you can modify the paths that ArcGIS checks. You can add the folder to sys.path in Python directly in individual scripts or more permanently by modifying the PYTHONPATH environment variable.

You can also set arcpy.env.workspace to the appropriate folder that contains the toolbox, but I'm not sure why that would be more beneficial that just supplying the full path.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.