Home >Backend Development >Python Tutorial >Python 执行字符串表达式函数(eval exec execfile)

Python 执行字符串表达式函数(eval exec execfile)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-16 08:42:541409browse

仔细研读后学习了三个函数:
eval:计算字符串中的表达式
exec:执行字符串中的语句
execfile:用来执行一个文件

需注意的是,exec是一个语句,而eval()和execfile()则是内建built-in函数。

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x=1
>>> print eval("x+1")
2
>>> exec "print 'http://blog.leniy.org/python-eval-exec-execfile.html'"
http://blog.leniy.org/python-eval-exec-execfile.html
>>> 

同时,我们有时使用input输入一些数据,例如

>>> input("请输入:")
请输入:1+2**3
9
>>> 

其实这里的input也是eval的应用,等效于

>>> eval(raw_input("请输入:"))
请输入:1+2**3
9
>>> 
Statement:
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