Python中eval,exec这两个函数有着相似的输入参数类型和执行功能,因此在用法上经常出现混淆,以至经常用错,程序易抛出错误。下面主要通过这两个函数的语法来阐述区别,并用例子来进一步说明。

首先看下官方文档对这两个函数的说明:

(1)eval(expr, globals=None, locals=None, /)

Evaluate the given expr in the context of globals and locals.

This call returns the expr result.

The expr may be a string representing a Python expression

or a code object as returned by compile().

The globals must be a dictionary and locals can be any mapping,

defaulting to the current globals and locals.

If only globals is given, locals defaults to it.

(2)exec(stmts, globals=None, locals=None, /)

Execute the given stmts in the context of globals and locals.

The stmts may be a string representing one or more **Python statements**
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.

特别注意上述黑体字,发现eval与exec的第一个输入参数虽然都是string,但eval中的是表达式,而exec中的是声明,所以区分这两个函数的问题就转化成了什么是表达式,什么是声明的问题,这两个概念必须搞清楚,才能理清楚这两个函数的用法。

Python中,表达式有比如比较大小,数字相乘,列表切片,函数调用等等,而声明则比较特殊,有assignment statement,expression statement(call function,instance method etc),print statement,if statement,for statement,while statement,def statement,try statement...

注意到表达式与声明存在某些交集,如函数调用,实例方法调用,print等,因此对于这些交集,都可以传入这两个函数,而除此之外,最好将expression传入eval,而statement传入exec,否则,要么抛出异常,要么不能实现既定的目标。

接下来用实例来阐述。

eval('x=1')#赋值声明,传入eval报错
  File "<string>", line 1
x=1
^
SyntaxError: invalid syntax
exec('x=1');x
1
eval('1<2')#比较表达式
True
exec('1<2');print('No output')#表达式,没有输出
No output
eval('print("print can be shown via eval")')
print can be shown via eval
exec('print("print can also be shown via exec")')
print can also be shown via exec

Python中eval与exec用法的区别的更多相关文章

  1. python中eval()和json.loads的区别

    一.最近在写接口测试脚本时,发现当读取Excel用例时,有时候要用eval,有时候又要用json.loads,不知道区别,只能换一下就可以用了,不知道其中的原理,特地百度了下.于是就记录了下,以便后续 ...

  2. python中sort和sorted用法的区别

    Python list内置sort()方法用来排序,也可以用python内置的全局sorted()方法来对可迭代的序列排序生成新的序列 一,最简单的排序 1.使用sort排序 my_list = [3 ...

  3. Python中__get__ ,__getattr__ ,__getattribute__用法与区别?

    class C(object): a = 'abc' def __getattribute__(self, *args, **kwargs): print("__getattribute__ ...

  4. Python中sorted()方法的用法

    Python中sorted()方法的用法 2012-12-24 22:01:14|  分类: Python |字号 订阅 1.先说一下iterable,中文意思是迭代器. Python的帮助文档中对i ...

  5. python中import和from...import...的区别

    python中import和from...import...的区别: 只用import时,如import xx,引入的xx是模块名,而不是模块内具体的类.函数.变量等成员,使用该模块的成员时需写成xx ...

  6. Linux中yum和apt-get用法及区别

    Linux中yum和apt-get用法及区别   一般来说著名的linux系统基本上分两大类:   1.RedHat系列:Redhat.Centos.Fedora等   2.Debian系列:Debi ...

  7. 转发 python中file和open有什么区别

    python中file和open有什么区别?2008-04-15 11:30地痞小流氓 | 分类:python | 浏览3426次python中file和open有什么区别?都是打开文件,说的越详细越 ...

  8. Html A标签中 href 和 onclick用法、区别、优先级别

    原文:Html A标签中 href 和 onclick用法.区别.优先级别 如果不设置 href属性在IE6下面会不响应hover.双击后会选中标签的父容器而非这个一a标签(IE下都存在这一问题). ...

  9. Python中 sys.argv[]的用法

    Python中 sys.argv[]的用法 因为是看书自学的python,开始后不久就遇到了这个引入的模块函数,且一直在IDLE上编辑了后运行,试图从结果发现它的用途,然而结果一直都是没结果,也在网上 ...

随机推荐

  1. C 语言入门第十二章---C语言文件操作

    C语言具有操作文件的能力,比如打开文件.读取和追加数据.插入和删除数据.关闭文件.删除文件等. 在操作系统中,为了同意对各种硬件的操作,简化接口,不同的硬件设备也都被看成一个文件.对这些文件的操作,等 ...

  2. c++中的运算符重载operator1(翁恺c++公开课[30]学习笔记)

    运算符重载规则: 只有已经存在的运算符才能被重载,不能自己制造一个c++中没有的运算符进行重载 重载可以在类或枚举类型内进行,也可以是全局函数,但int.float这种已有的类型内是不被允许的 不能二 ...

  3. Java1.7已经舍弃substr了

    网上一堆在写substring和substr区别的文章,都是过时的. 起码在官方6.0的api文档中已经找不到了,只有substring()

  4. JS html页面

    js窗口置顶 if (window != top) top.location.href = location.href; js打开新窗口 js window.open()弹出窗口参数说明及居中设置 f ...

  5. myBatis mapper接口方法重载问题

    在mybatis框架中,写dao层的mapper接口时,是不可以进行方法的重载的,下面是截图证明:   当mapper接口中有方法的重载时,会出现异常,   这是mapper接口中定义的两个方法,进行 ...

  6. 38 java 使用标签跳出多层嵌套循环

    public class Interview { public static void main(String[] args) { //使用带标签的break跳出多层嵌套循环 Boolean flag ...

  7. A way to use NAT network by using Oracle virtualBox

    That is true. Vmware  is easy and confortable tools to make vitrual machines than Oracle virtual box ...

  8. vue中配置sass(包含vue-cli 3)

    目录 vue vue cli 3 老版本的脚手架搭建的项目 版本 安装 不用修改任何配置 vue文件中使用 vue 更新时间: 2018-09-21 vue cli 3 选择 Manually sel ...

  9. redis 之redis集群与集群配置

    一.为什么要用集群 redis3.0集群采用P2P模式,完全去中心化,将redis所有的key分成了16384个槽位,每个redis实例负责一部分slot,集群中的所有信息通过节点数据交换而更新. r ...

  10. Write-up-Bulldog2

    关于 下载地址:点我 哔哩哔哩:哔哩哔哩 信息收集 网卡:vboxnet0,192.168.56.1/24,Nmap扫存活主机发现IP为192.168.56.101 ➜ ~ nmap -sn 192. ...