Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple positional arguments with Python and argparse

I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot of the namespace each time a positional argument is found), but the problem I'm having can be replicated with the append action:

>>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('-a', action='store_true') >>> parser.add_argument('-b', action='store_true') >>> parser.add_argument('input', action='append') >>> parser.parse_args(['fileone', '-a', 'filetwo', '-b', 'filethree']) usage: ipython [-h] [-a] [-b] input ipython: error: unrecognized arguments: filetwo filethree 

I'd like this to result in the namespace (a=True, b=True, input=['fileone', 'filetwo', 'filethree']), but cannot see how to do this - if indeed it can. I can't see anything in the docs or Google which says one way or the other if this is possible, although its quite possible (likely?) I've overlooked something. Does anyone have any suggestions?

like image 659
Blair Avatar asked Mar 21 '11 03:03

Blair


1 Answers

You can't interleave the switches (i.e. -a and -b) with the positional arguments (i.e. fileone, filetwo and filethree) in this way. The switches must appear before or after the positional arguments, not in-between.

Also, in order to have multiple positional arguments, you need to specify the nargs parameter to add_argument. For example:

parser.add_argument('input', nargs='+') 

This tells argparse to consume one or more positional arguments and append them to a list. See the argparse documentation for more information. With this line, the code:

parser.parse_args(['-a', '-b', 'fileone', 'filetwo', 'filethree']) 

results in:

Namespace(a=True, b=True, input=['fileone', 'filetwo', 'filethree']) 
like image 194
srgerg Avatar answered Oct 10 '22 12:10

srgerg