'for' loop in embedded Python

Michael P. Reilly arcege at shore.net
Mon Sep 27 13:53:46 EDT 1999


Randy Heiland <heiland at ncsa.uiuc.edu> wrote:
: I'm simply wondering if I can use a 'for' loop in an embedded Python pgm
: via PyRun_SimpleString, as in the following example pgm.  In general,
: how does it know about indentation/end of loop?

: #include "Python.h"

: #include <import.h>
: #include <graminit.h>
: #include <pythonrun.h>

: main(int argc, char **argv)
: {
:  Py_Initialize();

:  printf("Hello, brave new world\n\n");

:  /* Execute some Python statements (in module __main__) */

:  PyRun_SimpleString("idx=0\n");
:  PyRun_SimpleString("s=0\n");
:         printf("--- did s=0\n");
:  PyRun_SimpleString("print range(3)");
:         printf("--- did print range(3)\n");
:  PyRun_SimpleString("for idx in range(5):\n");
:         printf("--- did for\n");
:  PyRun_SimpleString("s=s+idx\n");
:         printf("--- did sum\n");
:  PyRun_SimpleString("\n");
:  PyRun_SimpleString("print s\n");
:         printf("did print s\n");

:  /* Some more application specific code */
:  printf("\nGoodbye, cruel world\n");

:  /* Exit, cleaning up the interpreter */
:  Py_Exit(0);
: }

Unfortunately, you need to place the entire loop body in the SimpleString
call:
  PyRun_SimpleString("for idx in range(5):\n  s=s+idx\n");

: ---------------------------------
: I get a  SyntaxError :
: Hello, brave new world

: --- did s=0
: [0, 1, 2]
: --- did print range(3)
:   File "<string>", line 1
:     for idx in range(5):
:                                  ^
: SyntaxError: unexpected EOF while parsing

The primary reason you get a syntax error is because it expects more
text (on the next line, indented), but the end of string is acting like
an end-of-file (when compiling the statement).

  -Arcege





More information about the Python-list mailing list