PyRun_String("if True: 1\nelse: 0", Py_eval_input, globals, globals);
returns error with PyErr_Print() printing out:
File "<string>", line 1
if Tru开发者_Python百科e: 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.
It does, but you're not doing anything that will produce output or return a value.
Consider the following code:
#!/usr/bin/python
def foo():
if True: 1
else: 0
a = foo()
print(a)
a will not get the value 0 or 1 - it will be 'None'.
加载中,请稍侯......
精彩评论