Monday, March 10, 2014

Embedding python in C.

Hi all,

Python is developing now a days. So as a developer we have to change based on the technology.

Now i am going to explain about how we can compile the python programs with(in) c.

Example python program:

addition.py

def add(a,b):
    c=a+b
    print "You did it and Added result is ..",c


And my C program:

samlepython.c

#include <Python.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
  Py_SetProgramName(argv[0]);  /* optional but recommended */
  Py_Initialize();
  PyRun_SimpleString("import addition\naddition.add(4, 2)\n");  /* here we are calling the python                                                                                                                                                 things */
  Py_Finalize();
  return 0;
}


Now you have to compile your c program:

gcc samlepython.c -o sample_python

it will show the following error:
"mainpgm.c:1:20: fatal error: Python.h: No such file or directory"

For this you have add your python installed location to your gcc.

gcc -I/usr/include/python2.7 -lpython2.7 samplepython.c -o sample_python

now it compiled and if you are running the ./sample_python means; you will get the foollowing error.

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named addition


It means the program is not able to find the imported "addition" location. for this you have to add the path folder to PYTHONPATH variable.

Suppose i stored my program under the /home/cool/docs/

export PYTHONPATH="/home/cool/docs/"

then again compile and once again run your program,
Output:
You did it and Added result is .. 6


Yeah you compiled your python program with c. Congratz...:)



Regards,
cooldharma06..:)



1 comment:

  1. Hi,

    I need to pass a string in which I have stored a wav file to my python program

    #include

    char tmp1[200];

    int main()

    {

    int i; int j = 1;

    char tmp[200];

    Py_Initialize();

    PyRun_SimpleString("import sys; sys.path.append('.')");

    PyRun_SimpleString("import naya;");

    //PyRun_SimpleString("import pyfile;");

    #if 1

    while (1) {

    /* Add audio record code here */

    sprintf(tmp, "arecord --device=hw:1,0 -d 5 --format S16_LE --rate 44100 -c1 %d.wav", j);

    system(tmp);

    sprintf(tmp1, "%d.wav", j);

    /* might have to add a delay here */

    PyRun_SimpleString("print naya.temp((tmp1))"); /*search how to pass string variable*/

    // naya is my python program for which the wav file is the input

    I am getting Name Error: name 'tmp1' is not defined. Could you please let me know how to proceed?

    Regards,
    Mithu

    ReplyDelete