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?