I want to parse two long command line options - a list of files and a command like so:
python example.py file1 file2 -- echo hello world
With a result of:
>>> args.filenames
["file1", "file2"]
>>> args.command
["echo", "hello", "world"]
Is this possible in argparse or any other python CLI library (such as docopt)?
In argparse, the --
means, treat everything that follows as positional strings. But all strings in your sample look like that, so the --
does nothing. So the remaining question is, how is argparse suppose to to allocate the 5 strings to 2 arguments. nargs=2
, and narg='*'
would do the trick if you always want 2 'files'. +
and REMAINDER
(...
) would also work for the 2nd.
What won't work is *
followed by *
. That would be akin to a RegEx pattern of '(a*)(a*)'
. In fact argparse uses RegEx pattern matching to allocate strings to positional arguments. Creating the 2 arguments, and trying various nargs
values can be instructive.
Another option is to replace the --
with an optionals argument, e.g. -c
with a nargs='*'
.