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. 【原】Linux中常见服务介绍

    1.SSH介绍 简单说,SSH(Secure Shell Protocol)是一种网络协议,用于计算机之间的加密登录.在默认状态下SSH服务提供俩个服务功能,一个是提供类似telnet远程联机服务器的 ...

  2. Java基础 -4.5

    循环控制 在循环语句定义的时候还有两个控制语句:break.continue break主要的功能是退出整个循环结构 continue严格来讲只是结束当前的一次调用(结束当前循环) 当执行到了cont ...

  3. spring mvc注解之@RequestBody和@RequestParm

    @RequestBody http://localhost:8080/user/login { "username":"jack", "passwar ...

  4. PHP PDO_MYSQL 链式操作 非链式操作类

    <?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ // +-------------------------------------- ...

  5. 创建私有yum仓库

    创建私有yum仓库

  6. uniGUI 应用程序体系结构(11)

    下图表示 uniGUI 服务器的内部结构. 每个 uniGUI 服务器都有一个ServerModule的副本, 每台服务器创建一次, 同时根据用户活动动态创建和销毁多个Session. uniGUI ...

  7. 对于JAVA语言的一点理解

    java作为一门面向对象的语言,现在常常被用于企业服务器端的后台开发.同时,C语言可能更多地是用于嵌入式的开发,所谓的嵌入式就是航天飞机上的设备软件之类的东西.但是,我逐渐发现,我们平时所说的java ...

  8. Lesson 9 Royal espionage

    What important thing did King Alfred learn when he penetrated the Danish camp of Guthrum? Alfred the ...

  9. C语言动静态链接库使用(笔记)

    看了视频一直没空写........... C静态链接库不用说了跟你写在cpp文件里的函数一样不会有单独的模块 不再赘述生活中用的比较少 例子 .h文件 int Plus(int x, int y); ...

  10. JS 删除对象中指定的值

    1,通过delete删除 2,通过filter filter需要在循环的时候判断一下是true还是false,是true才会返回这个元素: let arr1 = [1,2,3]; let arr2 = ...