I have this python code that runs other code and I can get the result as such:
def codeTester():
try:
loc = {}
exec(code, {}, loc)
except Exception as e:
#Excpetion handling....
result = loc['result']
loc after running would be a dictionary and result key would have the output of the function.
However this does not work with recursive functions. According to Using exec() with recursive functions and Python3: inject a recursive function into exec() in a function I need to wrap the code which I do using the function inside the second link:
def wrap(s):
return "def foo():\n" \
"{}\n" \
"foo()".format(textwrap.indent(s, ' ' * 4))
This wraps the 'code' with that function and now The recursive code runs but loc[] does not hold the result. It just holds a key called 'foo' which has this value <function foo at 0x000001F208386F70>. How can I get the output in this situation? or is there a better method to achieving this?
edit: I should note that something like exec(code, locals(), locals())
does also work but its still the same problem where I cant access the output of exec()