python convert a string to arguments list

后端 未结 3 899
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  忘了有多久
    2021-02-08 13:34

    You can use the string as an argument list directly in an call to eval, e.g.

    def func(**args):
    for a in args:
        print( a, args[a])
    
    s='a=2, b=3'
    
    eval('func(' + s + ')')
    >>>b 3
    >>>a 2
    

    note that func needs to be in the namespace for the eval call to work like this.

提交回复
热议问题