I want to share an ArcMap Python Toolbox which requires some additional Python package. Since the package is 100 % Python, I was able to use it by copying the Github repository to my computer. Within the Toolbox script, I added
import sys
sys.path.append("/absolute/path/to/parent/folder")
which added the folder containing the package to the Python path. This works when using the Toolbox locally, with an absolute path to the package location.
However, when I share the Toolbox, I have to copy the package together with the other toolbox files and to use relative paths.
I found multiple approaches to this: here, here, and here. None of them worked for me.
These are examples of what I tried:
import sys
# one of
# 1
this_dir = os.path.dirname(os.path.abspath("../"))
# 2
this_dir = os.path.dirname(os.path.abspath(__file__))
# 3
this_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
# 4
import inspect
this_dir = inspect.getfile(inspect.currentframe())
# followed by
main_dir = os.path.dirname(this_dir)
sys.path.append(main_dir)
import spectral # = name of the package
In any of these cases, the Toolbox did not find the package. So, how can I get the Toolbox script directory in an ArcMap Python Toolbox?
I managed to import by copying the package folder next to the .pyt file.
Then I added
import os, sys
main_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(main_dir)
which apparently solved the issue.