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. 吴裕雄 Bootstrap 前端框架开发——Bootstrap 显示代码

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  2. Kali中文乱码问题

    上面的是用网上介绍的安装组件无法安装,老是提示最后一句:Unable to locate package ...... 后来觉得应该是因为安装Kali时在最后有个选择更新系统的一个配置上,我选择了下面 ...

  3. Java基础 -5

    方法的定义与使用 方法(method)的基本定义 本次方法定义在主类之中并且由主方法直接调用,所以方法的定义语法形式如下: public static 返回值类型 方法名称([参数类型 变量, ... ...

  4. Codeforces Round #594 (Div. 2) - C. Ivan the Fool and the Probability Theory(思维)

    题意:给n*m的网格涂黑白两种颜色,保证每个格子上下左右的四个格子中最多只有一个格子与自己颜色相同,问有多少种涂法?结果$mod1000000007$ 思路:先只考虑一行有多少种涂法 $dp[i][0 ...

  5. Codeforces Round #579 (Div. 3)D(字符串,思维)

    #include<bits/stdc++.h>using namespace std;char s[200007],t[200007];int last[200007][27],nxt[2 ...

  6. VUE引入模块之import xxx from 'xxx' 和 import {xxx} from 'xxx'的区别

    import FunName from ‘../xxx’ export defualt function FunName() { return fetch({ url: '/article/list' ...

  7. freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...]

    FreeMarker template error:The following has evaluated to null or missing:==> product  [in templat ...

  8. C-当把数组传递给函数

    #include <stdio.h> /** * C语言中,数组的名称就是 一连串连续内存的起始地址, * 因此给数组传递给函数,传递的就是数组元素类型的指针 */ ]); void he ...

  9. Java日志介绍(2)-Log4j

    Log4j是Apache的一个开源项目,官网地址为http://logging.apache.org/log4j/1.2/index.html.通过使用Log4j,可控制日志信息输出到控制台.文件.数 ...

  10. 一 注册功能&登录功能,权限拦截

    注册功能: 前端JSP:提供表单注册信息以及访问路径,发送请求到Strus2. Struts2 : 通过模型驱动接收并封装User对象,Spring依赖注入(无参构造+setter方法)获取业务层Us ...