Multiple optional position args with argparse.ArgumentParser

Some Unix filters accept zero, one or two positional arguments to represent inputs and outputs. I have such a script which does this. The ArgumentParser bit looks like this:

    parser = argparse.ArgumentParser()
    parser.add_argument("infile", default=None, nargs="?")
    parser.add_argument("outfile", default=None, nargs="?")
    options, _args = parser.parse_known_args()

This works as expected, but the help output doesn’t look quite right to me:

% heictopnm -h
usage: heictopnm [-h] [infile] [outfile]

positional arguments:
  infile
  outfile

options:
  -h, --help  show this help message and exit

An outfile is only a possibility if the infile is present, so there should be some nesting in the help output, like this:

usage: heictopnm [-h] [infile [outfile]]

Am I missing something? Is there actually a way to give an output file on the command line while reading input from sys.stdin?

1 Like

I think it’s quite standard for it to look like that. If I see grep explained as

grep -A[NumberOfLines(n)] [search] [file]  

or

grep -R [Search] [directory]

my natural interpretation is “If I supply 1 argument it’s the first optional field, if I supply 2 arguments I specify both optional fields.”

If you must think of it that way, [infile] [outfile] is shorthand for [infile [outfile]].

1 Like