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?

1 Answer 1

3
+100

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
$
Sign up to request clarification or add additional context in comments.

6 Comments

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.
Sure it does. If that packages reads sys.argv as your question suggests, that function is what you're looking for.
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...
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.
I've added a full example.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.