Reference a script/model from within the same Toolbox

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.


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