Rectangle 27 0

Python argparse: nargs + or * depending on prior argument?


% test.py --odas
If you are making a server query, you must pass an address.
% test.py --odam
Namespace(address=['master1.odamex.net:15000', 'master2.odamex.net:15000'], query_type='odam')
% test.py --odam 1 2 3
Namespace(address=['1', '2', '3'], query_type='odam')
import argparse
import sys

class AddressAction(argparse.Action):
    def __call__(self, parser, args, values, option = None):
        args.address=values
        if args.query_type=='odam' and not args.address:
            args.address=[
                'master1.odamex.net:15000',
                'master2.odamex.net:15000',
                ]        
        if not args.address:
            parser.error("If you are making a server query, you must pass an address.")

p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
        const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
        const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*', action=AddressAction)
args = p.parse_args()
sys.exit()

One downside of using a custom action is that the action is called when the argument is parsed, and arguments after the one in question have not yet been added to the values array. This makes optional arguments sensitive to order. To avoid this, dont add a custom action, just check the dependency after the main call to parse_args, and call p.error('explanation message') if the dependecy fails. This prints out the help text and exits.

Precisely what I was looking for!

You can do this with an custom argparse.Action:

Note