Monday, 17 December 2018

Adding arbitrary code to ArcGIS ModelBuilder?


Is there any way to add arbitrary code snippets to an ArcGIS model?


I envision something similar to the "show code block" the expression builder in advanced labelling or field calculator.


For example my project of the moment could benefit greatly from fetching the username of the person running the tool. I know in python this is a simple import os; os.environ.get('USERNAME'). I think I could write that snippet to get_username.py, add it to a toolbox in Arccatalog, then add that tool to the model and use it as per-requisite model parameter for my current tool. That's a lot of work for such a small thing, and next time I might want something else, like inline variable substitution or a compound variable.


I think a code snippet tool or similar could be address all of these needs in a generic, broadly helpful manner.



Answer



New answer to an old post, just to clarify how to create a re-usable model to do this.


Open the model, Insert-> Model Only Tools-> Calculate Value.


In the Expression, type: getuser()



In the Code Block, type:


def getuser():
import getpass
return getpass.getuser()

(See "Getting user name in specific format" for source of username code snippet from @ChadCooper)


For Data Type, choose String.


enter image description here


Rename the output circle to username. The end-result model will look like: Using Calculate Value tool


And you can then just drag this model into any future models and reference the variable called %username% in any future models or scripts. Just be sure this model runs before you try to access the %username% variable. You can do this by using a precondition.



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