Search code examples
pythonpython-2.7python-c-api

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 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?


Solution

  • 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
    $