Argparse with required subparser

前端 未结 1 1110
执笔经年
执笔经年 2020-11-28 08:19

I\'m using Python 3.4, I\'m trying to use argparse with subparsers, and I want to have a similar behavior to the one in Python 2.x where if I don\'t supply a po

相关标签:
1条回答
  • 2020-11-28 09:05

    You need to give subparsers a dest.

    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='cmd')
    subparsers.required = True
    

    Now:

    1909:~/mypy$ argdev/python3 stack23349349.py
    usage: stack23349349.py [-h] {foo} ...
    stack23349349.py: error: the following arguments are required: cmd
    

    In order to issue this 'missing arguments' error message, the code needs to give that argument a name. For a positional argument (like subparses), that name is (by default) the 'dest'. There's a (minor) note about this in the SO answer you linked.

    One of the few 'patches' to argparse in the last Python release changed how it tests for 'required' arguments. Unfortunately it introduced this bug regarding subparsers. This needs to be fixed in the next release (if not sooner).

    update

    If you want this optional subparsers behavior in Py2, it looks like the best option is to use a two stage parser as described in

    How to Set a Default Subparser using Argparse Module with Python 2.7

    There has been some recent activity in the related bug/issue

    https://bugs.python.org/issue9253

    update

    A fix to this is in the works: https://github.com/python/cpython/pull/3027

    0 讨论(0)
提交回复
热议问题