pythonargparsepositional-argument

How to make argparse treat all arguments as positional?


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.


Solution

  • 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