I am trying to implement an command line argument with argparse in a way that only none or once is accepted. Multiple occurences should be rejected.
I use the following code
#!/usr/bin/env python3
import argparse
cmd_parser = argparse.ArgumentParser()
cmd_parser.add_argument('-o', dest='outfile')
cmd_line = cmd_parser.parse_args()
print(cmd_line.outfile)
One argument gives the expected result:
./test.py -o file1
file1
When issuing the argument twice, the first occurence is silently ignored:
./test.py -o file1 -o file2
file2
I also tried nargs=1
and action='store'
without reaching the desired result.
How can I tell argparse to reject multiple argument occurances?
It could be arranged with a custom Action:
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)
You can specify a default:
% script.py
/tmp/out
You can specify -o
once:
% script.py -o file1
file1
But specifying -o
twice raises an error:
% script.py -o file1 -o file2
usage: script.py [-h] [-o OUTFILE]
script.py: error: -o can only be specified once
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With