zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python内置函数compile用法详解

Python 详解 函数 用法 内置 compile
2023-09-11 14:15:15 时间

        python内置函数compile 可以将字符串编译成字节代码或者AST对象,字节代码对象可以被exec() 或 eval() 执行。

语法结构:

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

参数解析:

  • source 可以是字符串或者字节字符串,后者AST对象
  • filename 是代码读取的文件名,source是从哪个文件里读取的,就用哪个文件的名称,如果不是从文件读取的source,则填写一个可辨识值,一般用''
  • mode 编码模式,如果source是语句,则mode可以是exec,如果是单一表达式,则可以是eval,如果source是单个交互式语句,mode可以是single
  • flags 和 dont_inherit 用来控制编译源码时的标志,一般情况下使用默认值

示例代码1:

aa = "3*5+6"
code = compile(aa, 'string', 'eval')
print(code)
print(eval(code))

运行结果:

示例代码2:

code_string = """
def func():
    print('123456')
    return '666'
func()
"""
code = compile(code_string, 'string', 'exec')
print(code)
print(exec(code))

运行结果:

        执行exec(code) 就如同执行了code_string所代表的代码,func函数会被调用,输出"123456"。

        如果source只是一个表达式,那么mode应当使用eval,执行编译后的字节码也用eval;如果source是python语句,那么mode应当使用exec,执行编译后的字节码也要用exec。

示例代码3:

import ast

code_string = ast.parse("print(666)")

code = compile(code_string, 'string', 'exec')
print(code)
print(exec(code))

运行结果: