简体   繁体   中英

Custom Action argparse Python

I would like to use the same custom action for 2 different arguments:

class TestAction(Action):

    def __call__(self, parser, namespace, values, option_string=None):
        car, color, state, code = values
        namespace.car = car
        namespace.color = color
        namespace.state = state
        namespace.code = code

When I am defining the arguments, I would like to define them as follows:

    parser.add_argument('--vehicle', nargs="2", action=TestAction, metavar=('car', 'color'), required=True)
    parser.add_argument('--country', nargs="2", type=tuple(str, int), action=TestAction,metavar=('state', 'code'), required=True)

If I am using the custom action as it is written, I am getting the following error:

ValueError: not enough values to unpack (expected 4, got 2)

I've been trying to define some dummy '_' and fill the empty values with "_" when unpacking, but it didn't worked. The second issue is that I would like to force the code to be integer and the syntax tuple(str, int) is not correct. Any ideas how can I correct these 2 issues? Thanks.

I think the easier way is to use something like this (without argparse.Action ):

import argparse


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('car', type=str)
    parser.add_argument('color', type=str)
    parser.add_argument('state', type=str)
    parser.add_argument('code', type=int)
    args = parser.parse_args()
    print(args)

The output:

py .\test.py acar acolor acountry 1
>>> Namespace(car='acar', code=1, color='acolor', state='acountry')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM