Taking an input from Python into a C++ program

时间:2015-05-24 21:21:57

标签: python c++ wrapper extending

I'm working on a program that wraps a C++ program that mutates a nucleotide sequence with Python. I'm much more familiar with python then I am with C++ and parsing data files is easier for me using Python.

How do I take a string that I've parsed in Python, and use that as an input to the C++ program? The C++ program by itself already takes strings, input by users, as an input.

3 个答案:

答案 0 :(得分:1)

You can launch your python script as a separate process and get its complete output. In QT you can do this this way for example:

QString pythonAddress = "C:\\Python32\\python.exe";
QStringList params;

params << "C:\\your_script.py" << "parameter2" << "parameter3" << "parameter4";

p.start(pythonAddress, params);
p.waitForFinished(INFINITE);
QString p_stdout = p.readAll().trimmed(); // Here is the process output.

If you are not QT familiar, use platform specific process manipulations techniques or boost. Check this out:

How to execute a command and get output of command within C++?

How to create a process in C++ on Windows?

Execute a process and return its standard output in VC++

答案 1 :(得分:0)

If you mean calling a program from Python and doing something with its output, then you want the subprocess module.

If you want to expose your C++ function directly to Python, then I'd suggest checking out Boost.Python.

答案 2 :(得分:0)

Do you want to take the output of a python program and use it as input to a C++ program?

You could just use the shell for that:

python ./program.py | ./c_program  

Do you want to execute a python program from within C++ and get the output back as a string?
There are probably better ways to do it, but here is a quick solution:

//runs in the shell and gives you back the results (stdout and stderr)
std::string execute(std::string const& cmd){
    return exec(cmd.c_str());
}
std::string execute(const char* cmd) {
    FILE* pipe = popen(cmd, "r");
    if (!pipe) return "ERROR";
    char buffer[128];
    std::string result = "";
    while(!feof(pipe)) {
        if(fgets(buffer, 128, pipe) != NULL)
            result += buffer;
    }
    pclose(pipe);
        if (result.size() > 0){
    result.resize(result.size()-1);
    }
    return result;
}

std::string results_of_python_program = execute("python program.py");