Answer a question

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)

Answers

I find your first solution to be the right one. The reason is that it allows you to better handle defaults:

names: List[str] = ['Jane', 'Dave', 'John']

parser = argparse.ArumentParser()
parser.add_argument('--names', default=names, action=SplitArgs)

args = parser.parse_args()
names = args.names

This doesn't work with list_str because the default would have to be a string.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐