1

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 can run it like this:

python my_py_app input.txt --option1="value1" --option2="value2"

Here's what I've been doing:

1, Setup python API using Py_Initialize();

2, Load that package using PyImport_ImportModule("my_py_app") and it returns a valid PyObject

3, I don't know how to proceed ...

The python C API document contains lots of functions like PyEval_CallXXX. Which one do I need to call and how do I pass the option/value pairs to the program?

Jay Zhao
  • 946
  • 10
  • 24

1 Answers1

3

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
$
Community
  • 1
  • 1
kichik
  • 33,220
  • 7
  • 94
  • 114
  • Thank you, I've checked that question before posting mine. The problem is that my_py_app is not a py file, it is a python package (folder) so the answer there seems not applicable to me. – Jay Zhao Jan 12 '14 at 07:50
  • Sure it does. If that packages reads `sys.argv` as your question suggests, that function is what you're looking for. – kichik Jan 12 '14 at 08:54
  • 1
    Let's say I've set the arguments using PySys_SetArgv, but what's next? In the question you give, there is FILE* file = fopen("mypy.py","r"); PyRun_SimpleFile(file, "mypy.py"); but I don't have a file so it seems I can not call PyRun... – Jay Zhao Jan 12 '14 at 09:04
  • If you call that function and then import the module like you already do, it should give the module the parameters and it should work. If not, you can always create a small script that wraps the package and call that using the example code from the other question. – kichik Jan 12 '14 at 09:31
  • 1
    I've added a full example. – kichik Jan 12 '14 at 20:18
  • I was wondering how to run the python package without calling Py_RunXXX. Your great example clearly explains that! – Jay Zhao Jan 13 '14 at 01:35