argparse argument post-processing

Dom Grigonis dom.grigonis at gmail.com
Mon Nov 27 06:29:01 EST 2023


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.

---------

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.

Any ideas appreciated,
Regards,
DG



More information about the Python-list mailing list