argparse argument post-processing

Mats Wichmann mats at wichmann.us
Mon Nov 27 14:55:35 EST 2023


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}") 









More information about the Python-list mailing list