'Python argparse custom argument format

Whats' the simplest way to extend argparse to make it accept arguments like --nameVALUE instead of --name=value like this:

myprog --userXXX

{user='XXX'}

I've monkeypatched _parse_optional this way:

import argparse 
from functools import partial

class MyAction(argparse.Action):
    def __init__(self, dest):
        super().__init__([], dest)

    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, values)


def create_argparser():
    parser = argparse.ArgumentParser(description = 'Test actions')

    def parse_optional(arg_string, key, cls, orig):
        if not arg_string.startswith('--' + key):
            return orig(arg_string)
        return cls(key), key, arg_string[len(key) + 2:]

    parser._parse_optional = partial(parse_optional, key = 'debug', cls = MyAction, orig = parser._parse_optional)
    parser._parse_optional = partial(parse_optional, key = 'verbose', cls = MyAction, orig = parser._parse_optional)
    return parser

if __name__ == '__main__':
    args = create_argparser().parse_args()
    print(args)

Works like this:

python.exe argtest.py --debugXA --verboseXXX
Namespace(debug='XA', verbose='XXX')

Can it be done with less keytyping?



Sources

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

Source: Stack Overflow

Solution Source