目录
- compile() 函数是什么
- 语法
- 参数
- 示例
- 总结
compile() 函数是什么
compile() 函数将一个字符串编译为字节代码。
compile将代码编译为代码对象,应用在代码中可以提高效率。
语法
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
参数
- source:表示要编译的源代码字符串、AST对象或代码对象。
- filename:表示源代码的文件名。如果源代码不是从文件中读取的,可以使用一个虚拟的文件名。
- mode:表示编译模式,可以指定为 exec, eval, single。
- flags:可选参数,用于指定编译时的标志。可以使用ast.PyCF_*常量进行按位或运算的组合,用于控制编译过程中的不同行为。
- dont_inherit:可选参数,如果设置为True,则编译时不会继承当前作用域的符号表。
- optimize:可选参数,指定编译优化级别的标志。默认值为-1,表示使用默认优化级别。
返回表达式执行结果。
示例
首先code下新建demo.py
from code.cal import add,mul from code.sqrt import sqrt __all__ =[ "add","mul","sqrt"]
cal.py
def add(a,b): return a+b def mul(a,b): return a*b
sqrt.py
def sqrt(a): return a**2
编写调用脚本test.py
import traceback
import os
import requests
import threading
import time
import json
import logging
log=logging.getLogger()
def compile_funcs(codefile,funname_list):
"""
Args:
codefile: Path of Python's Code file
funname_list: list of function names
Return: dict of func info
"""
try:
#读取代码
with open(codefile) as f:
code=f.read()
#将字符串编译为字节代码
methods_obj=compile(code,"","exec")
scope = {}
'''
exec函数族的作用是根据指定的文件名找到可执行文件,并用它来取代调用进程的内容;
换句话说,就是在调用进程内部执行一个可执行文件。这里的可执行文件既可以是二进制文件,
也可以是任何Linux下可执行的脚本文件
'''
exec(methods_obj,scope)
fun_object={}
for name in funname_list:
fun_obj= scope.get(name,None)
fun_object[name] = fun_obj
return fun_object
except Exception as e:
traceback.print_exc(e)
return None
#函数名称
func_lists=['add','mul','sqrt']
#传入code下的demo.py
func_dict= compile_funcs("./code/demo.py",func_lists)
#获取返回对象
add = func_dict['add']
mul = func_dict['mul']
sqrt = func_dict['sqrt']
#传参调用
c = add(2,3)
d = mul(3,3)
e = sqrt(5)
print(f"add(2,3)={c}")
print(f"mul(3,3)={d}")
print(f"sqrt(5)={e}")结果:
add(2,3)=5
mul(3,3)=9
sqrt(5)=25
总结
compile() 函数的应用场景包括:
1、动态执行代码:可以将源代码字符串编译为代码对象,然后使用exec()函数执行。
2、动态求值表达式:将单个表达式编译为代码对象,然后使用eval()函数求值。
3、AST分析和修改:将源代码字符串编译为AST对象,然后使用ast模块进行分析和修改操作,例如静态代码分析、代码转换等。
在使用某些代码需要提炼出公共的代码块是可以使用,方便后续的使用和添加;
到此这篇关于关于compile() 函数简单实用示例的文章就介绍到这了,更多相关compile() 函数实用示例内容请搜索本网站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本网站!
您可能感兴趣的文章:
- 10分钟教你用Python实现微信自动回复功能
- python实现微信自动回复功能
- python itchat实现微信自动回复的示例代码
- 利用python微信库itchat实现微信自动回复功能
- python实现微信小程序自动回复
- python微信公众号之关键词自动回复
- python实现微信机器人: 登录微信、消息接收、自动回复功能
- Python中re.compile函数的使用方法
- Python正则表达式re.compile()和re.findall()详解
- Python 正则 re.compile 真的必需吗
- Python中请不要再用re.compile了
- python内置函数compile(),complex()的使用