引言
题主原本以为这种问题GPT应该能简单应对,没想到好几个GPT给出的代码都是错的,特记录如下。
特别声明:题主运行机器为Ubuntu22.04系统,不同机器的系统调用不完全相同,请仔细甄别。
关键函数
popen: 开启一个进程(process)运行特定的命令,并打开一个管道。
相关介绍:popen(3) - Linux manual page (man7.org)
强调:根据官方手册,开启的管道仅允许读"r"或者写"w",不允许同时读写。这一点绝大部分GPT都会犯错。
对于既有输入又有输出的Python程序,一个比较简单的办法是使用echo命令进行输入。详情请看代码。
代码
bool pyRun(const std::string file_name, const std::string input, std::string& output){
//make command.
std::string command = "echo \'" + input + "\' | python3 " + file_name;
FILE* pipe = popen(command.c_str(), "r");
if(!pipe){
std::cout << "Open python file failed, errono is " << errno << "." << std::endl;
return false;
}
output.clear();
char buffer[128];
while(fgets(buffer, 128, pipe) != nullptr){
output += buffer;
}
pclose(pipe);
return true;
}