'mixing positional and optional arguments in argparse

I am facing a problem in argparse when I mix positional arguments , optional arguments and argparse.REMAINDER

parser = argparse.ArgumentParser()
parser.add_argument('verbose', action="store")
parser.add_argument('--config', '-c', nargs="?", dest="config_file")
parser.add_argument('--dry-run', action="store_true", dest="dryrun")
parser.add_argument('args', nargs=argparse.REMAINDER, action="store")

Sample run:

python test.py verbose="5" --config config.xml graph --dry-run

Expected output:

verbose = "5"
config_file = config.xml
dryrun = True
args = ['graph']

Actual output:

verbose = "5"
config_file = config.xml
dryrun = False
args = ['graph', '--dry-run']

My requirement is I have verbose, -c, --config and --dry-run as command line options and any other options provided at command line should be stored in the list args irrespective of the order of appearance of arguments at command line. Please help where I am doing wrong. Also is there any other better command line parser for python?



Solution 1:[1]

I'd say the configuration you need is this:

    parser.add_argument('--verbose', action="store")
    parser.add_argument('-c', '--config', nargs="?", dest="config_file")
    parser.add_argument('--dry-run', action="store_true", dest="dryrun")
    parser.add_argument('args', nargs='*')

I think the "REMAINDER" argument you gave specifically tells the argparse module to take the rest of the arguments in args, when it finds the first argument it cannot match to the rest.

If you want 0 or more arguments for args use '*', if you want at least 1 arg use '+' as nargsargument.

Other than that I would recommend the argparse documentation as there are a lot of possibilities to already parse with the needed type (e.g. int or file arguments). Also creating a CLI-argparsemodule in the free Aptana Studio provides a good wrapper for argparse with some of the standard arguments (like verbose) already set. Verbose in that case would be a level as integer.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1