0

Is it possible to use a custom python toolbox (pyt) in a scripting environment (arcpy). For example I have created a .pyt toolbox and want to be able to call the individual tools in a scripting environment. Can one import the toolbox something like import example.pyt and then call the tools?

thanks for any information.

user44796
  • 1,053
  • 1
  • 11
  • 20
  • 1
    The way you do this is to create a normal python module that happens to have a .pyt file that relies on the functions and class in the module. Here's an example: https://github.com/Geosyntec/python-propagator – Paul H Aug 01 '22 at 18:23

2 Answers2

1

In ArcGIS, there is a function available arcpy.ImportToolbox(PathToToolbox). This will allow importation of tools into an arcpy script.

Thomas
  • 8,357
  • 15
  • 45
  • 81
user44796
  • 1,053
  • 1
  • 11
  • 20
0

There are ways to load a module with other file extensions, however, if it is your own custom made toolbox, you should rather refactor your toolbox and keep the toolbox's functionality in a separate module which is then used by your toolbox and your external script. Paul H's comment points to a good example.

However, if you are not able to refactor the toolbox, then you could use the package importlib. Here is an example based on another SO answer:

For this example, consider that your toolbox.pyt has a function say_hello().

from importlib.util import spec_from_loader, module_from_spec
from importlib.machinery import SourceFileLoader 

spec = spec_from_loader("toolbox", SourceFileLoader("toolbox", r"/path/toolbox.pyt"))
toolbox = module_from_spec(spec)
spec.loader.exec_module(toolbox)

toolbox.say_hello()

In addition, adding sys.modules['toolbox'] = toolbox allows you to import toolbox in other Python files after above code run.

Note: IMHO, if you have a chance to refactor the toolbox, a refactoring should be preferred.

Thomas
  • 8,357
  • 15
  • 45
  • 81