Wirawan Purwanto
Wirawan Purwanto

Reputation: 4043

Python argparse treatment of multiple but identical flags

All,

I want to create an argument parser that would allow multiple specification of the same command-line option (think of the -e flag of grep: you can specify multiple regexps). Here is my test code:

parser = argparse.ArgumentParser(description="...my description...")
parser.add_argument("file", nargs="*",
                    help="email file(s) to process")
parser.add_argument("-i", "--input",
                    nargs=1, dest="input_list",
                    help="a text file containing filenames to process")
argp = parser.parse_args(args)

When args contains multiple -i option, for example: ['-i', 'file1', '-i', 'file2', 'arg1', 'arg2', 'arg3'], I only got 'file2' in the resulting namespace (argp.input_list).

Does argparse accommodate the case where input_list destination variable above can contain more than one values?

Wirawan

Upvotes: 1

Views: 575

Answers (1)

Sam Mason
Sam Mason

Reputation: 16164

action='append' is probably what you want, i.e:

parser = argparse.ArgumentParser(description="...my description...")
parser.add_argument("file", nargs="*",
                    help="email file(s) to process")
parser.add_argument("-i", "--input",
                    dest="input_list", action='append',
                    help="a text file containing filenames to process")
argp = parser.parse_args(['-i', 'file1', '-i', 'file2', 'arg1', 'arg2', 'arg3'])

gives me:

Namespace(file=['arg1', 'arg2', 'arg3'], input_list=['file1', 'file2'])

Upvotes: 1

Related Questions