4

I have an ArcGIS Toolbox with a bunch of parameters. A python script is used to perform some raster operations, based on this parameters. I am using Python argparse in the script to get the parameters. I do this because the program was originally developed as a command line tool using ArcPy. With argparse I can show some useful help text and use command line switches where the position of the argument in the argument list does not matter. Of course argparse offers much more advantages.

ArcGIS is passing the parameters as positional arguments. So I can't use parameters like -k or --doSomeThing=100

Using a checkbox for example, that is ticked, this will pass a "true" to my script but I would like to have a "real" command line switch like "-k" or something like that. Has anyone an idea if this is possible? Maybe using tool validation?

3
  • Short answer - No, ArcGIS will always pass parameters as as positional arguments.
  • Longer answer - Sort of, if you use a slightly hacky technique of accepting both positional arguments or options in your script, using the parse_known_args method.

Something like:

import argparse

def main(arg1,arg2,arg3):
    print arg1,arg2,arg3

parser = argparse.ArgumentParser(prog='MyCoolPythonTool')
parser.add_argument('-a', default='1')
parser.add_argument('-b', default='2')
parser.add_argument('-c', default='3')

# Fake some ArcGIS positional args
opts,args = parser.parse_known_args('4 5 6'.split())

if args: # ArcGIS has supplied the arguments in the correct order
    main(*args)
else: # args supplied on the command line
    main(opts.a, opts.b, opts.c)

# Fake some commandline options
opts,args = parser.parse_known_args('-a 9 -b 8 -c 7'.split())

if args: # ArcGIS has supplied the arguments in the correct order
    main(*args)
else: # args supplied on the command line
    main(opts.a, opts.b, opts.c)
1

An ArcGIS Toolbox provides you with a user interface in which you can set parameters as optional and handle them accordingly. This accomplishes the same thing as optional parameters with argparse that you are referring to. If you would like examples/clarification let me know and I will expand upon this with code examples from argparse and graphical/code examples from setting up an ArcToolbox.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.