简体   繁体   English

Python定义和调用字符串表示的函数

[英]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.

相关问题 有没有办法在 python 中将字符串定义为 function - Is there a way to define a string as a function in python 如何调用一个函数,它在python中的另一个函数中定义? - How to call a function, it define in another function in python? 如何在python 3中定义一个过程来调用函数 - How to define a procedure to call a function in python 3 在类中定义一个列表并调用它并在python的函数中使用它 - Define a list in class and call it and use it in a function in python 有没有办法通过字符串定义PYthon函数参数列表? - Is there a way to define a PYthon function parameter list by a string? 如何使用python从字符串定义函数 - how to define a function from a string using python 确定在python中表示为字符串的值的类型 - determine the type of a value which is represented as string in python python相当于'#define func()'或如何在python中注释掉函数调用 - python equivalent of '#define func() ' or how to comment out a function call in python 如何在Python中将字符串作为函数调用 - How to call a string as a function in Python 如何定义一个装饰器,它将为函数/方法调用提供插值的文档字符串 - How to define a decorator that will provide an interpolated doc string for a function/method call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM