Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add optional positional arguments with subparsers in argparse?

I'm trying to add a required input file name and an optional output file name to more than one subparser using the argparse module.

Here is my attempt:

# test_argparse.py

import argparse

def setup_parser():

    parser = argparse.ArgumentParser(prog='test_argparse.py',
                            formatter_class=argparse.RawDescriptionHelpFormatter,
                            description='Testing the argparse module.')

    parser.add_argument('--version', action='version', version='%(prog)s 1.0')

    subparsers = parser.add_subparsers()
    parser_actionA = subparsers.add_parser('actionA')
    parser_actionB = subparsers.add_parser('actionB')
    parser_actionC = subparsers.add_parser('actionC')

    parser.add_argument('infile', nargs=1, help='input mesh file name')
    parser.add_argument('outfile', nargs='?', help='output mesh file name')

    return parser

if __name__ == '__main__':
    parser = setup_parser()
    args = parser.parse_args()
    print args

If I execute this:

python test_argparse.py actionA infile outfile

it doesn't work, and what I get is:

usage: test_argparse.py [-h] [--version]
                    {actionA,actionB,actionC} ... infile [outfile]
test_argparse.py: error: unrecognized arguments: infile
like image 479
Kevin Copps Avatar asked Jun 19 '12 19:06

Kevin Copps


1 Answers

Define a new parser with common arguments and pass it to subparsers as parents:

files = argparse.ArgumentParser(add_help=False)
files.add_argument('infile', nargs=1, help='input mesh file name')
files.add_argument('outfile', nargs='?', help='output mesh file name')

subparsers = parser.add_subparsers()
parser_actionA = subparsers.add_parser('actionA', parents=[files])
parser_actionB = subparsers.add_parser('actionB', parents=[files])
etc..
like image 55
georg Avatar answered Oct 31 '22 17:10

georg