Friday, March 14, 2014

Passing Parameters in From C to Pyhton.

Hi all,

Once again i come with some C and Python. Dont think its very new things. It just an upgraded post of the last post "Embedding Python in C".

In the last post you learned "how to Embed the Python code in C". Now i am going to explain how we can send some parameters from Python to C.

Example:

mypython.py

import sys

ca_one = str(sys.argv[1])
ca_two = str(sys.argv[2])
print "My command line args are " + ca_one + " and " + ca_two

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

int main(int argc,char *argv[])
{
    FILE* file;

    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PySys_SetArgv(argc, argv);
    file = fopen("mypython.py","r");
    PyRun_SimpleFile(file, "mypython.py");
    Py_Finalize();

    return 0;
}
  
Now compile your c program and pass some paramters *for mypython.py ( above sample code) you have to send two parameters.

Input:
./call cool dharma


Output:
My command line args are cool and dharma


Yeah..! You did this, like this you can pass your parameters from your C program to python code. :)


Regards,
cooldharma06..:)



No comments:

Post a Comment