argparse — requiring either 2 values or none for an optional argument

后端 未结 4 1004
你的背包
你的背包 2021-02-06 01:07

I\'m trying to make an optional argument for a script that can either take no values or 2 values, nothing else. Can you accomplish this using argparse?

# desired         


        
4条回答
  •  天涯浪人
    2021-02-06 01:23

    You'll have to do your own error checking here. Accept 0 or more value, and reject anything other than 0 or 2:

    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--action", nargs='*', action="store", help="do some action")
    args = parser.parse_args()
    
    if args.action is not None and len(args.action) not in (0, 2):
        parser.error('Either give no values for action, or two, not {}.'.format(len(args.action)))
    

    Note that args.action is set to None when no -a switch was used:

    >>> import argparse
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument("-a", "--action", nargs='*', action="store", help="do some action")
    _StoreAction(option_strings=['-a', '--action'], dest='action', nargs='*', const=None, default=None, type=None, choices=None, help='do some action', metavar=None)
    >>> args = parser.parse_args([])
    >>> args.action is None
    True
    >>> args = parser.parse_args(['-a'])
    >>> args.action
    []
    

提交回复
热议问题