简体   繁体   中英

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:

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. The natural choice here is to pass it the globals() dict, so that whatever names your exec defines get put into the global namespace.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM