评估字典变量的数学表达式
我正在做一些评估已作为 JSON 对象保存到文件中的日志数据的工作。 为了方便我的工作,我创建了 2 个小型 Python 脚本,它们根据正则表达式过滤掉记录的条目,并打印出事件中的多个字段。
现在我希望能够在打印字段时评估简单的数学运算。这样我就可以说类似的话
./print.py type download/upload
,它会打印类型和上传下载比率。我的问题是我无法使用 eval()
因为这些值实际上位于 dict
内。
有一个简单的解决方案吗?
I'm doing some work evaluating log data that has been saved as JSON objects to a file.
To facilitate my work I have created 2 small python scripts that filter out logged entries according to regular expressions and print out multiple fields from an event.
Now I'd like to be able to evaluate simple mathematical operations when printing fields. This way I could just say something like
./print.py type download/upload
and it would print the type and the upload to download ratio. My problem is that I can't use eval()
because the values are actually inside a dict
.
Is there a simple solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
eval
可以选择采用globals
和locals
字典。因此,您可以这样做:请记住,
eval
是“邪恶的”,因为如果执行的字符串不可信,则它是不安全的。不过,这对于你的帮助脚本来说应该没问题。为了完整性,还有
ast.literal_eval()
,它更安全,但它只评估文字,这意味着无法给它一个字典。eval
optionally takes aglobals
andlocals
dictionaries. You can therefore do this:Keep in mind that
eval
is "evil" because it's not safe if the executed string cannot be trusted. It should be fine for your helper script though.For completness, there's also
ast.literal_eval()
which is safer but it evaluates literals only which means there's no way to give it a dict.您可以将
dict
作为locals
传递给eval()
。这将允许它将download
和upload
解析为名称(如果它们是dict
中的键)。You could pass the
dict
toeval()
as thelocals
. That will allow it to resolvedownload
andupload
as names if they are keys in thedict
.