argparse argument post-processing
Dom Grigonis
dom.grigonis at gmail.com
Mon Nov 27 15:21:14 EST 2023
Thank you, exactly what I was looking for!
One more question following this. Is there a way to have a customisable action? I.e. What if I want to join with space in one case and with coma in another. Is there a way to reuse the same action class?
Regards,
DG
> On 27 Nov 2023, at 21:55, Mats Wichmann via Python-list <python-list at python.org> wrote:
>
> On 11/27/23 04:29, Dom Grigonis via Python-list wrote:
>> Hi all,
>> I have a situation, maybe someone can give some insight.
>> Say I want to have input which is comma separated array (e.g. paths='path1,path2,path3') and convert it to the desired output - list:
>> import argparse
>> parser = argparse.ArgumentParser()
>> parser.add_argument('paths', type=lambda x: list(filter(str.strip, x.split(','))))
>> So far so good. But this is just an example of what sort of solution I am after.
>
> Maybe use "action" rather than "type" here? the conversion of a csv argument into words seems more like an action.
>
>> Now the second case. I want input to be space separated array - bash array. And I want space-separated string returned. My current approach is:
>> import argparse
>> parser = argparse.ArgumentParser()
>> parser.add_argument('paths', nargs='+')
>> args = parser.parse_args()
>> paths = ' '.join(args.paths)
>> But what I am looking for is a way to do this, which is intrinsic to `argparse` module. Reason being I have a fair amount of such cases and I don’t want to do post-processing, where post-post-processing happens (after `parser.parse_args()`).
>> I have tried overloading `parse_args` with post-processor arguments, and that seemed fine, but it stopped working when I had sub-parsers, which are defined in different modules and do not call `parse_args` themselves.
>
> Depending on what *else* you need to handle it may or not may work here to just collect these from the remainders, and then use an action to join them, like:
>
> import argparse
>
> class JoinAction(argparse.Action):
> def __call__(self, parser, namespace, values, option_string=None):
> setattr(namespace, self.dest, ' '.join(values))
>
> parser = argparse.ArgumentParser()
> parser.add_argument('paths', nargs=argparse.REMAINDER, action=JoinAction)
> args = parser.parse_args()
>
> print(f"{args.paths!r}")
>
>
>
>
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list