exec官方声明This statement supports dynamic execution of Python code.

exec语句用来执行储存在字符串或文件中的python语句。exec 是一个语法声明,不是一个函数.也就是说和if,for一样。

exec函数是只执行语句代码,而不执行表达式代码,因为它没有任何返回值。

exec可以执行:

  1. 代码字符串
  2. 文件对象
  3. 代码对象
  4. tuple

 

>>> a=1
>>> g={'a':20}
>>> exec "print a" in g
20
>>> l={'b':10}
>>> b=2
>>> exec "print a+b "in g,l
30
>>> exec "global a;print a" in g
20
>>> a
1
>>> g.keys()
['a', '__builtins__']
>>> g.values
<built-in method values of dict object at 0x0000000002D9EBF8>
>>> g['a']
20

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-02-28
  • 2021-06-07
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-20
  • 2021-12-16
  • 2022-12-23
相关资源
相似解决方案