Python3.6内置函数(12)——compile()

浏览: 1405

英文文档

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object. Refer to the ast module documentation for information on how to work with AST objects.

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file (‘<string>’ is commonly used).

The mode argument specifies what kind of code must be compiled; it can be ‘exec’ if source consists of a sequence of statements, ‘eval’ if it consists of a single expression, or ‘single’ if it consists of a single interactive statement (in the latter case, expression statements that evaluate to something other than None will be printed).

compile()

1、将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。

2、参数source:字符串或者AST(Abstract Syntax Trees)对象。即需要动态执行的代码段。

3、参数 filename:代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。当传入了source参数时,filename参数传入空字符即可。

4、参数mode:指定编译代码的种类,可以指定为 ‘exec’,’eval’,’single’。当source中包含流程语句时,mode应指定为‘exec’;当source中只包含一个简单的求值表达式,mode应指定为‘eval’;当source中包含了交互式命令语句,mode应指定为’single’。

>>> #流程语句使用exec
>>> code1 = 'for i in range(0, 10):print (i)'
>>> compile1 = compile(code1, '', 'exec')
>>> exec(compile1)
0
1
2
3
4
5
6
7
8
9

>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
10
>>> #交互语句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3, '', 'single')
>>> name #执行前name变量不存在
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    name #执行前name变量不存在
NameError: name 'name' is not defined
>>> exec(compile3) #执行时显示交互命令,提示输入
please input your name:'python3.6.1'
>>> name #执行后name变量有值
"'python3.6.1'"

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,希望你留言和我进行交流、讨论。

欢迎关注微信公众号,访问更多精彩:数据之魅

如需转载,请联系授权,谢谢合作。

火狐截图_2019-06-29T07-07-45.688Z.png

推荐 0
本文由 Airy 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册