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

后端 未结 4 1002
你的背包
你的背包 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:36

    Have your option take a single, optional comma-separated string. You'll use a custom type to convert that string to a list and verify that it has exactly two items.

    def pair(value):
        rv = value.split(',')
        if len(rv) != 2:
            raise argparse.ArgumentParser()
        return rv
    
    parser.add_argument("-a", "--action", nargs='?',
                        type=pair, metavar='val1,val2',
                        help="do some action")
    print parser.parse_args()
    

    Then you'd use it like

    $ ./script.py -a
    Namespace(action=None)
    $ ./script.py -a val1,val2
    Namespace(action=['val1','val2'])
    $ ./script.py -a val1
    usage: tmp.py [-h] [-a [ACTION]]
    script.py: error: argument -a/--action: invalid pair value: 'val1'
    $ ./script.py -a val1,val2,val3
    usage: tmp.py [-h] [-a [ACTION]]
    script.py: error: argument -a/--action: invalid pair value: 'val1,val2,val3'
    

    You can adjust the definition of pair to use a different separator and to return something other than a list (a tuple, for example).

    The metavar provides a better indication that the argument to action is a pair of values, rather than just one.

    $ ./script.py -h
    usage: script.py [-h] [-a [val1,val2]]
    
    optional arguments:
      -h, --help            show this help message and exit
      -a [val1,val2], --action [val1,val2]
                            do some action
    

提交回复
热议问题