python-执行字符串代码

两种方式:
eval() 将字符串str当成有效的表达式来求值并返回计算结果。
exec() 跑多条语句,没有返回值

因此为了安全起见,要提供一个字典以充当命名空间。

命名空间:可以视为一个放置变量的地方。当你执行语句x=1时,将在当前命名空间存储键x和值1。当前命名空间通常是全局命名空间,但也并非必然如此。

安全问题

使用 ast.literal_eval
ast.parse
compile
dbm.dumb.open

命名空间

var = "This is a string"
varName = 'var'
s= locals()[varName]
s
'This is a string'
s2=vars()[varName]
s2
'This is a string'
s3=eval(varName)
s3
'This is a string'

locals是python的内置函数,他可以以字典的方式去访问局部和全局变量。
globals返回的是当前模块的全局变量 locals返回的是局部变量。注意,locals返回的是当前所在最小命名空间的局部变量的一个拷贝。

python里面用名字空间记录着变量

每个模块,每个函数都有自己的名字空间,记录着变量,常量,类的命名和值。
当python在使用变量时,会按照下面的步骤去搜索:

函数或类的局部变量。
全局变量。
内置变量。

for key in locals().keys():
print (key)

for value in locals().values():
print (value)

compile

Compile source into a code object that can be executed by exec() or eval().

exec()

from math import sqrt
scope={}
exec('sqrt=1',scope)
sqrt(4)
>>2.0
scope['sqrt']
>>1

eval()