embedded python in c - function

PixelDust1 pixeldust1 at NOSPAMPLEASEhotmail.com
Sat May 21 19:06:44 EDT 2005


Hi guys,

I am pretty new to Python and to embedding it in C.
Here is what I am trying to accomplish:

I have a C program that accepts user input, which can be
a Python script which includes functions defined by the user line by
line as typed in. Let me show the code that I have:

#include "Python.h"


main(int argc, char **argv)
{
	
	
	// Pass argv[0] to the Python interpreter 
	Py_SetProgramName(argv[0]);

	// Initialize the Python interpreter.  Required. 
	Py_Initialize();


	// Define sys.argv.  It is up to the application if you
	// want this; you can also let it undefined (since the Python 
	// code is generally not a main program it has no business
	// touching sys.argv...) 
	PySys_SetArgv(argc, argv);

	PyRun_SimpleString("def fib(n):\n");
	PyRun_SimpleString("\t\ta, b = 0, 1\n");
	PyRun_SimpleString("\t\t\while b < n:n");
	PyRun_SimpleString("\t\tprint b,\n");
	PyRun_SimpleString("\t\t\a, b = b, a+bn");
	PyRun_SimpleString("fib(2000)\n");


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

}

The code gives me the following:

  File "<string>", line 1
    def fib(n):
              ^
SyntaxError: unexpected EOF while parsing
  File "<string>", line 1
    a, b = 0, 1
    ^
SyntaxError: invalid syntax
  File "<string>", line 1
    while b < n:n
    ^
SyntaxError: invalid syntax
  File "<string>", line 1
    print b,
    ^
SyntaxError: invalid syntax
  File "<string>", line 1
    , b = b, a+bn
    ^
SyntaxError: invalid syntax
Traceback (most recent call last):
  File "<string>", line 1, in ?


Could anybody help me out by either pointing to a tutorial that deals
with this type of embedding to point out my mistakes in the code!

Thanks!



More information about the Python-list mailing list