Skip to content Skip to sidebar Skip to footer

Pass Command Line Arguments To Python 2.7.6 Package Application Using C Api

I'm new to python and now I need to call a python 2.7.6 program using its C API. The python program is in the form of a python package and takes several command line options. You c

Solution 1:

You're looking for the PySys_SetArgv function.

The following question has some more information and an example:

Run a python script with arguments


$ find
.
./py.c
./mymod
./mymod/__init__.py
./mymod/__main__.py
$ cat ./mymod/__init__.py
$ cat ./mymod/__main__.py
import sys

print'hello', ' '.join(sys.argv[1:])
$ python mymod world
hello world
$ cat ./py.c
#include <stdio.h>#include <python2.7/Python.h>

int main(void)
{
    int argc;
    char * argv[2];

    argc = 2;
    argv[0] = "mymod";
    argv[1] = "world";

    Py_SetProgramName(argv[0]);
    Py_Initialize();
    PySys_SetArgv(argc, argv);
    PyImport_ImportModule("mymod.__main__");
    Py_Finalize();

    return 0;
}
$ gcc `python2.7-config --cflags --ldflags` py.c
$ ./a.out
hello world
$

Post a Comment for "Pass Command Line Arguments To Python 2.7.6 Package Application Using C Api"