0

I have below python script which if I run with Python 2.7.16 version then I get an error but if I run with Python 3 version then it works fine.

Below is my code:

from argparse import ArgumentParser

def parse_cli_arguments():
    parser = ArgumentParser(
        description='some stuff'
    )
    parser.add_argument(
        "-v",
        "--verbose",
        help="verbose output",
        action="store_true"
    )
    subparser = parser.add_subparsers(
        title="action",
        dest='action',
        required=True,
        help='action sub-command help'
    )

    # create the subparser for the "push" command
    parser_push = subparser.add_parser(
        'push',
        help='push help'
    )
    parser_push.add_argument(
        'environment',
        type=str,
        help='push environment help'
    )
    parser_push.add_argument(
        'instance',
        type=str,
        help='push instance help'
    )
    parser_push.add_argument(
        'config',
        type=str,
        help='push config help'
    )

    # create the subparser for the "status" command
    parser_status = subparser.add_parser(
        'status',
        help='status help'
    )
    parser_status.add_argument(
        'environment',
        type=str,
        help='status environment help'
    )
    parser_status.add_argument(
        'instance',
        type=str,
        help='status instance help'
    )
    return parser

def main():
    parser = parse_cli_arguments()
    args = parser.parse_args()
    if args.action == 'push':
        print('You chose push:', args.environment, args.instance, args.config)
    elif args.action == 'status':
        print('You chose status:', args.environment, args.instance)
    else:
        print('Something unexpected happened')


if __name__ == '__main__':
    main()

Problem Statement

Below is the error I am getting with Python 2.7.16 version. Any thoughts what wrong am I doing here?

I need to run my above code on Python 2.7.16 version.

❯ python test.py
Traceback (most recent call last):
  File "test.py", line 70, in <module>
    main()
  File "test.py", line 59, in main
    parser = parse_cli_arguments()
  File "test.py", line 17, in parse_cli_arguments
    help='action sub-command help'
  File "/Users/andy/.pyenv/versions/2.7.16/lib/python2.7/argparse.py", line 1678, in add_subparsers
    action = parsers_class(option_strings=[], **kwargs)
TypeError: __init__() got an unexpected keyword argument 'required'

Do I need to change some syntax here to make it work with Python2?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
AndyP
  • 527
  • 1
  • 14
  • 36
  • `subparsers` used to be `required` by default, like a regular `positional`. The `required` option in Py3 has a long history. https://stackoverflow.com/questions/22990977/why-does-this-argparse-code-behave-differently-between-python-2-and-3; https://stackoverflow.com/questions/23349349/argparse-with-required-subparser – hpaulj Jan 08 '21 at 04:18

1 Answers1

3

The api between 2.7 and 3 has changed. sub_parsers did not previously have the required keyword arg.

Heres the function signature in the 2.7. docs

ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_string][, dest][, help][, metavar])

and here it is in the 3.9 docs

ArgumentParser.add_subparsers([title][, description][, prog][, parser_class][, action][, option_string][, dest][, required][, help][, metavar])

A workaround is suggested by @hpaulj which involves setting the required attribute after the add_subparsers call. You can find the answer (and leave any upvotes) here and here.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61