2
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.

David
  • 65
  • 4

2 Answers2

4

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.

Duncan
  • 92,073
  • 11
  • 122
  • 156
  • I'm new to python. I tried "1 if True else 0" and it works. Thanks. – David May 27 '11 at 09:22
  • I thought of suggesting that but wrongly assumed that you wouldn't be playing with the C-api until you had some experience with Python itself. BTW, if you are doing more than just running a simple expression or statement consider using Cython instead of using the C-api directly. – Duncan May 27 '11 at 09:38
0

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'.

synthesizerpatel
  • 27,321
  • 5
  • 74
  • 91