I need to pass a function in command line and parsing with argparse. How can I do that?
Eg.
python program.py --params a=range(1, 10, 1), b=range(2, 5, 1)...
I've tested:
parser.add_argument('-p', "--params", type=json.loads)
But when I try to launch cmd:
python program.py --p {"a": range(1, 10, 1}
returns this error:
error: argument -p/--params: invalid loads value: '{"a": range(1,10,1)}'
CodePudding user response:
you should create your own custom function for that and pass it in type
e.g.
>>> def hyphenated(string):
... return '-'.join([word[:4] for word in string.casefold().split()])
...
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument('short_title', type=hyphenated)
>>> parser.parse_args(['"The Tale of Two Cities"'])
Namespace(short_title='"the-tale-of-two-citi')
more info: here