argparse limitations

Oscar Benjamin oscar.benjamin at
Fri Jul 27 16:43:59 CEST 2012

On 27 July 2012 15:26, Benoist Laurent <benoist at> wrote:

> Hi,
> I'm impletting a tool in Python.
> I'd like this tool to behave like a standard unix tool, as grep for
> exemple.
> I chose to use the argparse module to parse the command line and I think
> I'm getting into several limitations of this module.
> > First Question.
> How can I configure the the ArgumentParser to allow the user to give
> either an input file or to pipe the output from another program?
> $ file.txt

$ cat file.txt |

A better way to do that last line is:
$ < file.txt

To answer the question, just make the first argument optional defaulting to
None. Then you can do:
if file1 is None:
    file1 = sys.stdin

> > Second Question.
> How can I get the nargs options working with subparser?
> Cause basically if I've got a positionnal argument with nargs > 1, then
> the subparsers are recognized as values for the positionnal argument.
> $ file1.txt file2.txt foo
> Here foo is a command I'd like to pass to mytool but argparse considers
> it's another input file (as are file1.txt and file2.txt).

I haven't used subparsers in argparse but I imagine that you would call it
$ foo file1.txt file2.txt


> Any help would be appreciated.
> Ben.
> --
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list