embedded python in c - function

P

PixelDust1

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top