I’d like to be able to evaluate arbitrary code from a string in Python, including code composed of multiple statements, and statements that span multiple lines. The approaches I’ve tried so far have been to use exec and eval, but these seem to only be able to evaluate expressions. I have also tried the code.InteractiveInterpreter class, but this also only seems to allow evaluation using eval, exec, or single-statement modes. I’ve tried splitting the code by line, but this fails to handle statements that span multiple lines. Is there a way to accomplish this?
I’d like to be able to evaluate arbitrary code from a string in Python,
Share
execseems to be what you are looking for:prints
eval()only handles expressions, butexechandles arbitrary code.