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
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With