简体   繁体   English

使用字符串作为Python中不完整的代码位

[英]Using strings as incomplete bits of code in Python

(please help me clarify the title) (请帮助我澄清标题)

This is what I'd like to do: 这就是我想做的事情:

s = "'arg1', 'arg2', foo='bar', baz='qux'"
def m(*args, **kwargs):
  return args, kwargs

args, kwargs = m(magic(s))
# args = ['arg1', 'arg2']
# kwargs = {'foo': 'bar', 'baz'='qux'}

What is the definition of magic()? magic()的解释是什么?

Parsing the string myself is a last resort since it's fraught with pitfalls (what if arg1 has a comma in it? what if arg2 has quotes in it? etc). 我自己解析该字符串是最后一招,因为它充满陷阱(arg1里面有逗号吗?arg2里面有引号怎么办?等等)。

With s and m defined as you have them: 使用sm定义它们:

>>> args, kwargs = eval('m(%s)' % s)
>>> args
('arg1', 'arg2')
>>> kwargs
{'foo': 'bar', 'baz': 'qux'}

看一下eval ,但是要注意,如果不小心,可能会发生不好的事情。

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

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