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. 【原】简单shell练习(四)

    1.查看已开启端口信息 #ss -ln 2.列出谁在使用某个端口(如:80) #lsof -i:80 3.显示文件夹下文件信息 #find /home/root -type f#find -type ...

  2. Python学习第十七课——组合

    组合1 #组合 1 class Hand: pass class Foot: pass class Trunk: pass class Head: pass class Person: def __i ...

  3. free to monitor your sqlserver easy and safe and ...

    Unlike AWR in Oracle, Sqlserver does not have offical way to make history performance information fo ...

  4. Centos7 mariadb (mysql)主从复制实现

    一.mysql基本命令 .启动mysql systemctl start mariadb .linux客户端连接自己 mysql -uroot -p -h 127.0.0.1 .远程链接mysql服务 ...

  5. CSS - 伪类和伪元素

    1. CSS3中 :Pseudo-classes 伪类 ::Pseudo-elements 伪元素 2. 为什么叫伪类和伪元素? 伪类的效果可以通过添加一个实际的类来达到,而伪元素的效果则需要通过添加 ...

  6. 已知空间三点组成的面求该面上某点的Z值

    已知空间三点,那么可以就可以确定空间三点组成的平面.此时可以根据某一点的X值和Y值,来求取该点在平面上的Z值.这个过程对于求三角面片上某点的高程或者权值特别有用,其本身也可以看作一种线性插值. 其算法 ...

  7. nrm 源管理器

    什么是nrm nrm 是一个 npm 源管理器,允许你快速地在 npm 源间切换. 安装nrm 在命令行执行命令,npm install -g nrm,全局安装nrm. 使用 执行命令nrm ls查看 ...

  8. Vue下URL地址栏参数改变却不能刷新界面

    在完成毕业设计(基于Vue的信息资讯展示与管理平台)的过程中,处理如下图所示的 点击左侧栏目列表跳转到对应文章列表 的问题时,初次点击可以跳转到对应的页面,但是当第二次点击时,虽然地址栏的参数改变了, ...

  9. 【剑指Offer面试编程题】题目1510:替换空格--九度OJ

    题目描述: 请实现一个函数,将一个字符串中的空格替换成"%20".例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy. 输入: 每个 ...

  10. Hadoop操作经验

    系统日志文件写入到MySQL中,NoSQL中一般存储独立的关联性不大的非业务数据. 单个NameNode也可以恢复,从SecondaryNameNode恢复:两个NameNode是可以做负载均衡:更高 ...