python exec函数_Python内置函数----exec

英文文档:

exec(object[, globals[, locals]])This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1] If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section “File input” in the Reference Manual). Be aware that the return and yieldstatements may not be used outside of function definitions even within the context of code passed to the exec() function. The return value is None.In all cases, if the optional parts are omitted, the code is executed in the current scope. If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables. If globals and localsare given, they are used for the global and local variables, respectively. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If exec gets two separate objects as globals and locals, the code will be executed as if it were embedded in a class definition.If the globals dictionary does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key. That way you can control what builtins are available to the executed code by inserting your own __builtins__ dictionary into globals before passing it to exec().NoteThe built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().NoteThe default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.说明:1. exec函数和eval函数类似,也是执行动态语句,只不过eval函数只用于执行表达式求值,而exec函数主要用于执行语句块。

copycode.gif

>>> eval('a=1+2') #执行语句报错

Traceback (most recent call last):

File "", line 1, in

eval('a=1+2')

File "", line 1

a=1+2

^

SyntaxError: invalid syntax

>>> exec('a=1+2') #执行语句

>>> a

3

copycode.gif

2. 第一个参数为语句字符串,globals参数和locals参数为可选参数,如果提供,globals参数必需是字典,locals参数为mapping对象。

3. globals参数用来指定代码执行时可以使用的全局变量以及收集代码执行后的全局变量

copycode.gif

>>> g = {'num':2}

>>> type(g)

>>> exec('num2 = num + 2',g)

>>> g['num']

2

>>> g['num2'] #收集了exec中定义的num2全局变量

4

copycode.gif

4. locals参数用来指定代码执行时可以使用的局部变量以及收集代码执行后的局部变量

copycode.gif

>>> g = {'num':2}

>>> type(g)

>>> l = {'num2':3}

>>> type(l)

>>> exec('''

num2 = 13

num3 = num + num2

''',g,l)

>>> l['num2'] #l中num2值已经改变

13

copycode.gif

5. 为了保证代码成功运行,globals参数字典不包含 __builtins__ 这个 key 时,Python会自动添加一个key为 __builtins__ ,value为builtins模块的引用。如果确实要限制代码不使用builtins模块,需要在global添加一个key为__builtins__,value为{}的项即可(很少有人这么干吧)。

copycode.gif

>>> g = {}

>>> exec('a = abs(-1)',g)

>>>

>>> g = {'__builtins__':{}}

>>> exec('a = abs(-1)',g) #不能使用内置函数了

Traceback (most recent call last):

File "", line 1, in

exec('a = abs(-1)',g)

File "", line 1, in

NameError: name 'abs' is not defined

copycode.gif

6. 当globals参数不提供是,Python默认使用globals()函数返回的字典去调用。当locals参数不提供时,默认使用globals参数去调用。

copycode.gif

>>> num = 1

>>> exec('num2 = num + 1')

>>> globals()

{'__package__': None, '__loader__': , '__name__': '__main__', '__spec__': None, '__builtins__': , '__doc__': None, 'num2': 2, 'num': 1}

>>>

>>>

>>> exec('num2 = num + 1',{}) #指定了globals参数,globals中无num变量 执行失败

Traceback (most recent call last):

File "", line 1, in

exec('num2 = num + 1',{})

File "", line 1, in

NameError: name 'num' is not defined

>>> l = locals()

>>> l

{'__package__': None, '__loader__': , '__name__': '__main__', '__spec__': None, '__builtins__': , '__doc__': None, 'l': {...}, 'num2': 2, 'num': 1}

>>>

>>> exec('num3 = num + 1',{},l)#指定了globals参数,globals中无num变量,指定了locals变量,locals变量含有num变量 执行成功

>>> l

{'__package__': None, '__loader__': , '__name__': '__main__', '__spec__': None, 'num3': 2, '__builtins__': , '__doc__': None, 'l': {...}, 'num2': 2, 'num': 1}

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值