[Python] argparse action or type for comma-separated list

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create a command line flag that can be used as

    ./prog.py --myarg=abcd,e,fg


    and inside the parser have this be turned into ['abcd', 'e', 'fg'] (a tuple would be fine too).

    I have done this successfully using action and type, but I feel like one is likely an abuse of the system or missing corner cases, while the other is right. However, I don't know which is which.

    With action:

    import argparse

    class SplitArgs(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
    setattr(namespace, self.dest, values.split(','))


    parser = argparse.ArgumentParser()
    parser.add_argument('--myarg', action=SplitArgs)
    args = parser.parse_args()
    print(args.myarg)


    Instead with type:

    import argparse

    def list_str(values):
    return values.split(',')

    parser = argparse.ArgumentParser()
    parser.add_argument('--myarg', type=list_str)
    args = parser.parse_args()
    print(args.myarg)

    Continue reading...

Compartilhe esta Página