|
| 1 | +import argparse |
| 2 | + |
| 3 | + |
| 4 | +class CustomAction(argparse.Action): |
| 5 | + def __init__(self, *args, **kwargs): |
| 6 | + argparse.Action.__init__(self, *args, **kwargs) |
| 7 | + print('initializing customAction') |
| 8 | + for name, value in sorted(locals().items()): |
| 9 | + if name == 'self' or value is None: |
| 10 | + continue |
| 11 | + print('\t{} = {!r}'.format(name, value)) |
| 12 | + print() |
| 13 | + |
| 14 | + def __call__(self, parser, namespace, values, option_string=None): |
| 15 | + print('Processing customAction for {}'.format(self.dest)) |
| 16 | + print('\tparser = {}'.format(id(parser))) |
| 17 | + print('\tvalues = {!r}'.format(values)) |
| 18 | + print('\toption_string = {!r}'.format(option_string)) |
| 19 | + |
| 20 | + if isinstance(values, list): |
| 21 | + values = [v.upper() for v in values] |
| 22 | + else: |
| 23 | + values = values.upper() |
| 24 | + setattr(namespace, self.dest, values) |
| 25 | + print() |
| 26 | + |
| 27 | + |
| 28 | +parser = argparse.ArgumentParser() |
| 29 | +parser.add_argument('-a', action=CustomAction) |
| 30 | +parser.add_argument('-m', nargs='*', action=CustomAction) |
| 31 | +results = parser.parse_args(['-a', 'value', '-m', 'multivalue', 'second']) |
| 32 | +print(results) |
| 33 | + |
0 commit comments