Argparse - How Pass To A Method With Kwargs Or Argv
I've been looking for a way to use **kwargs or *argv with argparse. I will from hard code to a dynamic way. Here is my hard code and a example how I will use it. def get_parser():
Solution 1:
Here, parameters
argument will have a list of 8 pairs, for example:
CLI.py -p argname1=v1 ... argname8=v8
(obviously argnameN
should be the argument names of the desired function).
You can then easily turn args.p
(which is ['argname1=v1', ... 'argname8=v8']
) into a dictionary:
defconvert_value(v):
try:
returnfloat(v) if'.'in v elseint(v)
except ValueError:
# v is not a numberreturn v
params = dict([convert_value(n) for n in pair.split('=')] for pair in args.p)
and pass it to your function:
"""Create a Template for a Job"""defcreate_Template(params):
#single GA job
logging.basicConfig(level=logging.DEBUG)
template = job.JobTemplate(runGASimple)
print tmpverb
template.setDefaults(**params)
return template
You can do the same with your range argument by creating two distinct range argument:
"""change Default params with AddRange"""defadd_Range(var_1, var_2, tmp_template):
jobCreator = job.JobCreator()
#jobCreator.addRange('temp0', start=0.0, end=1.0, stepSize=0.1)
jobCreator.addRange(**var_1)
#jobCreator.addRange('temp1', start=0.0, end=1.0, stepSize=0.1)
jobCreator.addRange(**var_2)
# all other params will take defaults
jobs = jobCreator.generateJobs(tmp_template)
Solution 2:
PLease pay attention at the Gall's answer - it might simplify your code dramatically. And regarding dynamic "argparse" please try this:
#!/usr/bin/env pythonfrom __future__ import print_function
from __future__ import unicode_literals
import argparse
args_d = {
'-r': {
'flags': ['-r', '--range'],
'nargs': 8,
'help': 'AddRange Parameters',
'dest': 'r'
},
'-p': {
'flags': ['-p', '--parameters'],
'nargs': 8,
'help': 'SetDefaults as Parameters',
'dest': 'p'
}
}
defsetup_parser(args_d):
parser = argparse.ArgumentParser()
for k,v in args_d.items():
if'flags'in v:
flags = v['flags']
del v['flags']
parser.add_argument(*flags, **v)
return parser
if __name__ == "__main__":
args = setup_parser(args_d).parse_args()
print(args)
You would still have to generate the dictionary dynamically. You can try to use the "inspect" module for that...
Post a Comment for "Argparse - How Pass To A Method With Kwargs Or Argv"