python - 如何使用已编译的 Code 对象创建 Function 对象?
问题描述
所以我有以下代码。
code_string = """def f1(p1, p2, p3):
print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
print("text")
"""
code = compile(code_string, '<string>', 'exec')
f1 = code.co_consts[0]
f2 = code.co_consts[2] # code.co_consts is the name of the prior function ("f1")
它将带有一些函数的字符串编译成代码对象,然后将函数的代码对象存储到单独的变量中。
我想知道的是如何使用上面的代码对象创建函数对象,以便我可以调用它们。
所以说ff1 = new_function(f1)
在哪里,我isinstance(ff1, types.FunctionType)
可以True
做ff1('a', 'b', 'c')
print "aa, bb, cc"
。
f1
中的代码对象f2
可以使用 exec 来执行。(虽然我不知道如何以f1
这种方式将参数传递给它们或用它们制作绑定方法)
解决方案
您可以使用exec(code)
and执行代码,f1
之后f2
您可以使用。
code_string = """def f1(p1, p2, p3):
print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
print("text")
"""
code = compile(code_string, '<string>', 'exec')
exec(code)
f1(1, 2, 3)
# a1, b2, c3
f2()
# text
请理解,将任意代码传递给exec()
(或evil eval()
)会带来严重的安全风险。
推荐阅读
- javascript - TypeError:无法读取未定义的scanner.js的属性“扫描”
- laravel - Laravel:分页后是否可以使用 eagerloading?
- blazor - 如何将 HTML 属性(类等)添加到 Blazor 组件?
- docker - “Docker-compose run”显示后端正在运行,但无法从主机访问
- android - Android:写日志文件的库?
- apache-spark - 将后缀附加到 PySpark 行
- kotlin - 使用 gradle 约定插件设置 kotlin jvmTarget 选项
- shell - 如何在shell中转换变量中的字符串
- lua - printf("%s\n", lua_tostring(L, -1)); 遇到分段错误
- php - 跳过修改 CTE 并返回现有键而不是插入新键(如果值已存在)