Python中的exec、eval使用实例

WBOY
Release: 2016-06-16 08:41:54
Original
1022 people have browsed it

通过exec可以执行动态Python代码,类似Javascript的eval功能;而Python中的eval函数可以计算Python表达式,并返回结果(exec不返回结果,print(eval("…"))打印None);

复制代码 代码如下:
  
>>> exec("print(\"hello, world\")")
hello, world

>>> a = 1
>>> exec("a = 2")
>>> a
2

这里有个scope(命名空间,作用域)的概念,为了不破坏现在的scope,可以新建一个scope(一个字典)执行exec(Javascript没有此功能):

复制代码 代码如下:

>>> scope = {}
>>> exec("a = 4", scope)
>>> a
2
>>> scope['a']
4
  
>>> scope.keys()
dict_keys(['a', '__builtins__'])

__builtins__包含了所有的内建函数和值;

而普通的{}不会包含__builtins__

复制代码 代码如下:

>>> a = {}
>>> a.keys()
dict_keys([])

同exec一样,eval也可以使用命名空间:

复制代码 代码如下:

>>> result = eval('2+3')
>>> result
5
>>> scope={}
>>> scope['a'] = 3
>>> scope['b'] = 4
>>> result = eval('a+b',scope)
>>> result
7
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!