Reputation: 970
I want to take written function (string) from a user input and convert it to a callable function in Python. How to achieve it despite any security concerns?
Example (string):
""" def test(): \n print('success') \n return 'success' """
I want to call / evaluate the said string by calling test() and make it print to the console.
Upvotes: 1
Views: 1394
Reputation: 1080
Try this, using the compile method combined with eval or exec:
a = compile("""def test(): \n print('success') \n return 'success' """, "", "exec")
eval(a)
test()
Upvotes: 2