What is the best way to parse python script file in C/C++ code

Posted by alexpov on Stack Overflow See other posts from Stack Overflow or by alexpov
Published on 2011-01-02T12:00:12Z Indexed on 2011/01/02 20:54 UTC
Read the original article Hit count: 388

Filed under:
|
|
|

I am embedding python in C/C++ program.

What I am trying to do is to parse the python script file from the C/C++ program, break the file to "blocks" so that each "block" is an a valid command in python code. Each block I need to put into std::string. For example:

#PythonScript.py

import math

print "Hello Python"
i = 0;
while (i < 10):
    print "i = " , i;
    i = i + 1;

print "GoodBye Python"

In this script are 5 different "blocks":

  • the first one is "import math;"
  • the second is "print "Hello Python;"
  • the third is "i = 0;"
  • and the fourth is

    while (i < 10):\n\tprint "i = " , i;\n\ti = i + 1;
    

My knowledge in python is very basic and I am not familiar with the python code syntax. What is the best way to do this, is there any Python C/C++ API function that supports this?


why i need it -> for GUI purpose. My program , which is writen in C, uses python to make some calculations. I run from C code , using python C API , python script and what i need is a way to capture python's output in my program. I catch it and evrything is ok, the problem is when the script involves user input. What happens is that i capture python's output after the script is finished , therefore, when there is an input command in the script i get a black screen .... i need to get all the printings before the input command.

The first solution i tried is to parss the script to valid commands and run each comand, one after the other , seperatly .... for this i need to pars the script and deside what is a command and what is not ... The question is : what is the best way to do this and if there is somthing that allready does ?

© Stack Overflow or respective owner

Related posts about c++

Related posts about python