将Python的输入输入到c++程序中

Taking an input from Python into a C++ program

本文关键字:输入 程序 c++ Python      更新时间:2023-10-16

我正在编写一个程序,该程序包装了一个用Python改变核苷酸序列的c++程序。我对python比c++更熟悉,使用python解析数据文件对我来说更容易。

我如何在Python中解析一个字符串,并将其用作c++程序的输入?c++程序本身已经接受用户输入的字符串作为输入。

您可以将python脚本作为一个单独的进程启动,并获得其完整的输出。在QT中,您可以这样做,例如:

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.

如果您不熟悉QT,请使用平台特定的进程操作技术或boost。看看这个:

如何在c++中执行命令并获得命令的输出?

如何在Windows上用c++创建进程?

在vc++中执行一个进程并返回它的标准输出

如果您的意思是从Python调用程序并对其输出进行处理,那么您需要subprocess模块。

如果你想将c++函数直接暴露给Python,那么我建议查看Boost.Python.

您想将python程序的输出用作c++程序的输入吗?

你可以直接使用shell:

python ./program.py | ./c_program  

你想在c++中执行一个python程序并得到一个字符串的输出吗?
可能有更好的方法,但这里有一个快速的解决方案:

//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");