'Convert a string to a callable function in Python
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.
Solution 1:[1]
When appropriate, this is a job for the exec function.
>>> exec("""def test(): \n print('success') \n return 'success' """, globals())
>>> test()
success
'success'
Solution 2:[2]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chepner |
| Solution 2 | maya |
