PyRun_String("if True: 1\nelse: 0", Py_eval_input, globals, globals);
returns error with PyErr_Print() printing out:
File "<string>", line 1
if True: 1
^
What am I doing wrong? Thank you.
That isn't a conditional expression: it's a statement. Py_eval_input
means to treat the string as a single expression. You probably want Py_single_input
to treat the string as a statement.
This is the same as the distinction in Python code between eval
(which is what you asked for) and exec
.
I am assuming of course that the statement you actually want to execute will be slightly more complex otherwise there isn't much point using either eval
or exec
. For exec
you'll want to make sure it has side effects so you can tell the result, e.g. by binding some value to a name.