为了完整起见,只需添加这个。我很惊讶我没有看到这种方法。
from argparse import Action, ArgumentParser
class CommaSeparatedListAction(Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values.split(','))
parser = ArgumentParser()
parser.add_argument('-l', action=CommaSeparatedListAction)
print(parser.parse_args('-l a,b,c,d'.split()))
# Namespace(l=['a', 'b', 'c', 'd'])
这只是一个基本示例,但您也可以以某种方式添加验证或转换值,例如将它们强制为大写。
from argparse import Action, ArgumentParser
class UppercaseLetterCommaSeparatedListAction(Action):
def __call__(self, parser, namespace, values, option_string=None):
letters = values.split(',')
for l in letters:
self._validate_letter(parser, l)
setattr(
namespace,
self.dest,
list(map(lambda v: v.upper(), letters))
)
def _validate_letter(self, parser, letter):
if len(letter) > 1 or not letter.isalpha():
parser.error('l must be a comma separated list of letters')
parser = ArgumentParser()
parser.add_argument('-l', action=UppercaseLetterCommaSeparatedListAction)
print(parser.parse_args('-l a,b,c,d'.split()))
# Namespace(l=['A', 'B', 'C', 'D'])
parser = ArgumentParser()
parser.add_argument('-l', action=UppercaseLetterCommaSeparatedListAction)
print(parser.parse_args('-l a,bb,c,d'.split()))
# usage: list.py [-h] [-l L]
# list.py: error: l must be a comma separated list of letters
parser = ArgumentParser()
parser.add_argument('-l', action=UppercaseLetterCommaSeparatedListAction)
print(parser.parse_args('-l a,1,c,d'.split()))
# usage: list.py [-h] [-l L]
# list.py: error: l must be a comma separated list of letters