sys.stdout = codeOut
sys.stderr = codeErr
exec(code)
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print(f(4))
s = codeErr.getvalue()
print('error:\n%s\n' % s)
s = codeOut.getvalue()
print('output:\n%s' % s)
codeOut.close()
codeErr.close()
How do I execute a string containing Python code in Python?