python convert a string to arguments list

后端 未结 3 779
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 12:39

Can I convert a string to arguments list in python?

def func(**args):
    for a in args:
        print a, args[a]

func(a=2, b=3)

# I want the following work li         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-08 13:27

    You want a dictionary, not an 'argument list'. You also would be better off using ast.literal_eval() to evaluate just Python literals:

    from ast import literal_eval
    
    params = "{'a': 2, 'b': 3}"
    func(**literal_eval(params))
    

    Before you go this route, make sure you've explored other options for marshalling options first, such as argparse for command-line options, or JSON for network or file-based transfer or persistence.

提交回复
热议问题