Friday, 19 July 2019

arcpy - Embedded python script module import issue


I have two ArcGIS python scripts. One is a primary python script that calls a number of functions from a second python script. Everything works well, i.e. primary tool calls and uses functions from a second script, when the two scripts are placed in the same directory and the primary python script is NOT embedded into python toolbox. However when the primary python script gets embedded into ArcGIS toolbox, the second script cannot be access any more by the primary script and therefore cannot be imported into the primary script as a module and functions cannot be used.


The work around would be to copy over all functions from the second script to the primary script or to copy second script into the toolbox directory but that is not the proper way to solve this issue.


Is it possible within ArcGIS to embed a script into a python toolbox with other scripts that are used by the primary script?



Answer



This is an issue with how python works. When you import a module, it will search for it in the built-in modules, the paths in sys.path and finally, the current working directory (Python Module Search Path).


You've already noticed that adding your second script to the same directory as the toolbox will allow your first, embedded script to import it. This is because you've put it in the working directory. Your other options are making it available to python in other ways (detailed in the docs I linked): Modifying sys.path from within the embedded script or creating/modifying the PYTHONPATH environment variable.



My guess is that ArcGIS simply stores the embedded python as text and executes it when needed. It has no way of knowing dependencies or what extra modules are imported. You would have this same problem if you used other 3rd party modules that were not part of the default installation.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...