How can I parse variable length argument lists delimited by special predefined syntax. An example:
./script --arg1 --cmdname otherscript --a1 --a2 --cmdname-- --arg3
After parsing with argparse script should have three arguments: arg1, cmdname, arg3. The argument cmdname should consist of a list of three values otherscript, a1, a2.
Having such a recipe would be useful to be able to pass on everything in cmdname into a subprocess.popen(cmdname, ...) call.
I was thinking about subparsers. But I believe a subparser cannot be stopped, and really is mutually exclusive with other subparsers. Any other easy, already provided way? Is subclassing the Action the way to do it?
As you indicated in your post, subclassing
Actionis probably the way to do this — Although that gets pretty tricky if the arguments tootherscriptaren’t known by argparse. You might be able to get around this withparse_known_args, but you might not. Honestly, I really think the easiest way is to preprocesssys.argvyourself.And an alternative implementation of
preprocesswhich works for sliceable objects that have a.indexmethod —sys.argvwould work just fine:Another option (pointed out in an excellent comment by @unutbu) is to change the commandline syntax to something a little more standard which simplifies the problem greatly:
Then you can parse
cmdas you normally would usingargparse(specifytype=shlex.splitfor this argument to convert from a string to a list of arguments).