它可以用一个自定义动作来安排:
import argparse
class Once(argparse.Action):
def __init__(self, *args, **kwargs):
super(Once, self).__init__(*args, **kwargs)
self._count = 0
def __call__(self, parser, namespace, values, option_string=None):
# print('{n} {v} {o}'.format(n=namespace, v=values, o=option_string))
if self._count != 0:
msg = '{o} can only be specified once'.format(o=option_string)
raise argparse.ArgumentError(None, msg)
self._count = 1
setattr(namespace, self.dest, values)
cmd_parser = argparse.ArgumentParser()
cmd_parser.add_argument('-o', dest='outfile', action=Once, default='/tmp/out')
cmd_line = cmd_parser.parse_args()
print(cmd_line.outfile)
您可以指定一个默认值:
% script.py
/tmp/out
您可以指定-o
一次:
% script.py -o file1
file1
但是指定-o
两次会引发错误:
% script.py -o file1 -o file2
usage: script.py [-h] [-o OUTFILE]
script.py: error: -o can only be specified once