在字典中使用eval而不会丢失Python2中导入的模块 [英] Use eval with dictionary without losing imported modules in Python2

查看:69
本文介绍了在字典中使用eval而不会丢失Python2中导入的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python程序中有一个要执行的字符串,我想将字符串中的某些变量(例如x [1],x [2])更改为其他变量.我以前曾将eval与2个参数一起使用(第二个参数是带有replaced_word:new_word的字典),但现在我注意到我不能使用以前导入的模块,例如.所以如果我这样做

I have a string to be executed inside my python program and I want to change some variables in the string like x[1], x[2] to something else. I had previously used eval with 2 arguments (the second being a dict with replaced_word: new_word) but now I noticed I can't use previously imported modules like this. So if I do this

from math import log
eval(log(x[1], {x[1]: 1})

它将说它不识别名称日志.如何在不丢失全局变量的情况下使用这样的eval?我不能真正理解文档: https://docs.python.org/2/library/functions.html#eval这样的解释也将很有用.

it will say it doesn't recognize the name log. How can I use eval like this without losing the global variables? I can't really make sense of the documentation: https://docs.python.org/2/library/functions.html#eval so an explanation would be useful too.

推荐答案

使用dict .html#globals"rel =" nofollow> globals() 作为基础:

Build your globals dict with globals() as a base:

from math import log

# Copy the globals() dict so changes don't affect real globals
eval_globals = globals().copy()
# Tweak the copy to add desired new global
eval_globals[x[1]] = 1

# eval using the updated copy
eval('log(x[1])', eval_globals)

或者,您可以使用三个参数 eval 使用未经修改的 globals(),而且还提供 local s的 dict ,该代码将首先在偏爱全局值:

Alternatively, you can use three-arg eval to use globals() unmodified, but also supply a locals dict that will be checked (and modified) first, in preference to global values:

eval('log(x[1])', globals(), {x[1]: 1})

从理论上讲,后一种方法可以允许表达式改变原始的全局变量,因此添加 .copy()使其成为 eval('log(x [1])',globals().copy(),{x [1]:1})可以最大程度地减少意外发生的风险.但是,病理/恶意代码可以解决此问题;毕竟, eval 是危险的,无论您如何制作沙盒,都不要相信它是任意输入的.

In theory, the latter approach could allow the expression to mutate the original globals, so adding .copy() to make it eval('log(x[1])', globals().copy(), {x[1]: 1}) minimizes the risk of that happening accidentally. But pathological/malicious code could work around that; eval is dangerous after all, don't trust it for arbitrary inputs no matter how sandboxed you make it.

这篇关于在字典中使用eval而不会丢失Python2中导入的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆