2

How can I make an argparse parser treat all arguments as positional, even the ones that look like options? For example, with this definition:

parser.add_argument('cmd', nargs='*', help='The command to run')

I want to be able to run

prog.py mycomand --foo arg

and have ['mycomand', '--foo', 'arg'] be captured as the cmd argument.

planetp
  • 14,248
  • 20
  • 86
  • 160
  • 3
    Why not use `sys.argv[1:]` if you want to capture everything? – modesitt Aug 13 '20 at 21:47
  • 1
    The program actually uses a lot of subparsers (to support subcommands), so I need `argparse`. – planetp Aug 14 '20 at 07:11
  • Can you use the [answer described here](https://stackoverflow.com/questions/37367331/is-it-possible-to-use-argparse-to-capture-an-arbitrary-set-of-optional-arguments) or do you need the parent parser to resolve well – modesitt Aug 14 '20 at 19:31
  • REMAINDER and -- can be used to force interpreting the remaining arguments as positional. See the docs – hpaulj Aug 14 '20 at 23:15

1 Answers1

1

It turned out I just needed to replace nargs='*' with nargs=argparse.REMAINDER. From the docs:

argparse.REMAINDER All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities.

This also works, but is less convenient:

prog.py mycomand -- --foo arg
planetp
  • 14,248
  • 20
  • 86
  • 160