开发者

Python C API: why doesn't PyRun_String evaluate simple conditional expressions?

开发者 https://www.devze.com 2023-03-08 14:34 出处:网络
PyRun_String(\"if True: 1\\nelse: 0\", Py_eval_input, globals, globals); returns error with PyErr_Print() printing out:
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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消