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').

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Oct 4, 2016 at 9:42

2 Answers 2

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.

answered Oct 4, 2016 at 13:08
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).

answered Oct 4, 2016 at 11:16

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.