python convert a string to arguments list

﹥>﹥吖頭↗ 提交于 2019-12-04 11:22:07

问题


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 like above code
s='a=2, b=3'
func(s)

I know:

list can, just use *list, but list can't have an element like: a=2

and eval can only evaluate expression

which would be like:

def func2(*args):
    for a in args:
        print a

list1=[1,2,3]
func2(*list1)
func2(*eval('1,2,3'))

回答1:


You could massage the input string into a dictionary and then call your function with that, e.g.

>>> x='a=2, b=3'
>>> args = dict(e.split('=') for e in x.split(', '))
>>> f(**args)
a 2
b 3



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/20263839/python-convert-a-string-to-arguments-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!