string - Python: Using run time inputs to change key values in a function -


import sys  def fun( a=7, b=1 ):     print a, b  fun() fun( a=5 ) fun( sys.argv[1:] ) 

the first fun() prints out '7,1', second prints out '5,1', third prints out '['a=8', 'b=6'] 1]'. able call program with

python my_program.py a=5 b=6 

to change value of printed , b. doesn't work since sys.argv[1] list of strings.

is there way convert the string list form function can understand?

use ** kwarg unpacking:

d = {} in sys.argv[1:]:     k, v = a.split('=')     d[k] = int(v) func(**d) 

another way, using csv module:

import csv func(**{k: int(v) k, v in csv.reader(sys.argv[1:], delimiter='=')}) 

as @martijnpieters noted may use argparse module

parser = argparse.argumentparser(description='process integers.') parser.add_argument('-a', type=int) parser.add_argument('-b', type=int)  args = parser.parse_args() fun(**dict(args._get_kwargs())) 

but have adjust way input arguments


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -