I'm trying to parse command-line arguments such that the three possibilities below are possible:
script
script file1 file2 file3 …
script -p pattern
Thus, the list of files is optional. If a -p pattern
option is specified, then nothing else can be on the command line. Said in a "usage" format, it would probably look like this:
script [-p pattern | file [file …]]
I thought the way to do this with Python's argparse
module would be like this:
parser = argparse.ArgumentParser(prog=base)
group = parser.add_mutually_exclusive_group()
group.add_argument('-p', '--pattern', help="Operate on files that match the glob pattern")
group.add_argument('files', nargs="*", help="files to operate on")
args = parser.parse_args()
But Python complains that my positional argument needs to be optional:
Traceback (most recent call last):
File "script", line 92, in <module>
group.add_argument('files', nargs="*", help="files to operate on")
…
ValueError: mutually exclusive arguments must be optional
But the argparse documentation says that the "*"
argument to nargs
meant that it is optional.
I haven't been able to find any other value for nargs
that does the trick either. The closest I've come is using nargs="?"
, but that only grabs one file, not an optional list of any number.
Is it possible to compose this kind of argument syntax using argparse
?