我正在开发一个程序,它包装了一个用Python改变核苷酸序列的C++程序。我更熟悉Python而不是C++,使用python解析数据文件对我来说更容易。
如何获取我在Python中解析的字符串,并将其用作C++程序的输入?C++程序本身已经将用户输入的字符串作为输入。
发布于 2015-05-25 05:25:09
您可以将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。看看这个:
How to execute a command and get output of command within C++?
发布于 2015-05-25 05:25:21
如果您的意思是从Python调用一个程序并对其输出做一些操作,那么您需要subprocess模块。
如果您想直接向Python公开您的C++函数,那么我建议您查看Boost.Python。
发布于 2015-05-25 05:37:30
您是否希望将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");https://stackoverflow.com/questions/30428458
复制相似问题