Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only one command line argument with argparse

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?

like image 896
sd2k9 Avatar asked Feb 16 '13 22:02

sd2k9


1 Answers

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
like image 118
unutbu Avatar answered Sep 22 '22 13:09

unutbu