argparse - Python parse_known_args with named arguments -
i pass arbitrary set of arguments in format --arg1 value1
python script , retrieve them in dictionary of kind {'arg1': 'value1}
. want use argparse
achieve that. function parse_known_args
allows args, can retrieved simple list , not named.
a better idea define one option takes 2 arguments, name , value, , use custom action update dictionary using 2 arguments.
class optionappend(action): def __call__(self, parser, namespace, values, option_string): d = getattr(namespace, self.dest) name, value = values d[name] = value p.add_argument("-o", "--option", nargs=2, action=optionappend, default={})
then instead of myscript --arg1 value1 --arg2 value2
, write myscript -o arg1 value1 -o arg2value1
, , after args = parser.parse_args()
, have args.o == {'arg1': 'value1, 'arg2': 'value2'}
.
this analogous use of list or dictionary hold set of related variables, instead of set of individually named variables.
# v = [x, y, z] v = { 'key1': x, 'key2': y, 'key3': z} # bad v1 = x v2 = y v3 = z
Comments
Post a Comment