[英]Python define and call function represented by string
Assume that we have a string假设我们有一个字符串
function_string = 'def main():\n\treturn(1)'
How can this be compiled as a function during runtime and then be executed?如何在运行时将其编译为函数然后执行?
This is my current attempt, unfortunately it raises a NameError expressing that main
is not defined:这是我目前的尝试,不幸的是它引发了一个 NameError 表示未定义
main
:
self.run():
exec(self.formatted_function_string) # similar to 'function_string' in the example
print(main())
As I said in the comments, executing / evaluating arbitrary strings is a security risk.正如我在评论中所说,执行/评估任意字符串是一种安全风险。 But if you really want to do this, you need to pass
exec
an appropriate globals dict.但是如果你真的想这样做,你需要向
exec
传递一个适当的全局字典。 The natural choice here is to pass it the globals()
dict, so that whatever names your exec
defines get put into the global namespace.这里的自然选择是将
globals()
dict 传递给它,以便您的exec
定义的任何名称都放入全局命名空间。
def test(argstring):
exec(argstring, globals())
print(main())
function_string = 'def main():\n\treturn(1)'
test(function_string)
print(main)
typical output典型输出
1
<function main at 0xb7196cd4>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.