简体   繁体   English

python将字符串转换为参数列表

[英]python convert a string to arguments list

Can I convert a string to arguments list in python? 我可以在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 list can,只需使用* list,但list不能有如下元素:a = 2

and eval can only evaluate expression 和eval只能评估表达式

which would be like: 这将是:

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

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

You could massage the input string into a dictionary and then call your function with that, eg 您可以将输入字符串按到字典中,然后用它调用您的函数,例如

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

You want a dictionary , not an 'argument list'. 你想要一个字典 ,而不是一个'参数列表'。 You also would be better off using ast.literal_eval() to evaluate just Python literals: 你也将被关闭使用更好的ast.literal_eval()来评估 Python文字:

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. 在开始这条路线之前,请确保首先探索了编组选项的其他选项,例如argparse用于命令行选项,或JSON用于网络或基于文件的传输或持久性。

You can use the string as an argument list directly in an call to eval , eg 您可以直接在eval调用中将字符串用作参数列表,例如

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. 请注意, func需要在命名空间中才能使eval调用像这样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM