python - 从 C++ 发出运行 python 脚本

标签 python c++

我正在尝试制作一个可以对 python 程序的输出进行评分的程序。我遗漏了一些简单的东西,但我一直在尝试将输出转换为字符串时遇到段错误。如果我将其保留为 char*,则工作正常,但我想要一个字符串,以便将来比较输出。 这是代码...

#include <iostream>
#include <string>
using namespace std;

string runPython(const char* filename) {
    string cmd = "python " + string(filename);
    char* buf;
    FILE* in = popen(cmd.c_str(), "r");
    fscanf(in,"%s", buf);
    string res(buf);
    pclose(in);
    return res;
}

int main(int argc, char** argv) {
    if(argc > 1) {  
        string res = runPython(argv[1]);
        printf("%s", res.c_str());
    }
    else {
        printf("\e[31mNo File Submitted for Grading\e[0m\n");
    }
    return 0;
}

最佳答案

你必须先分配缓冲区。

#include <iostream>
#include <string>
using namespace std;

#define MAX_READ 4096

string runPython(const char* filename) {
    string cmd = "python " + string(filename);
    char* buf = new char[MAX_READ]; // buffer allcoation
    FILE* in = popen(cmd.c_str(), "r");
    fscanf(in,"%s", buf);
    string res(buf);
    delete[] buf; // buffer release
    pclose(in);
    return res;
}

int main(int argc, char** argv) {
    if(argc > 1) {  
        string res = runPython(argv[1]);
        printf("%s", res.c_str());
    }
    else {
        printf("\e[31mNo File Submitted for Grading\e[0m\n");
    }
    return 0;
}

关于python - 从 C++ 发出运行 python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58108077/

相关文章:

python - Python 中从字符串末尾开始按 N 个符号分割字符串

python - 在 Python 中加载大型 JSON 列表的最佳方式是什么?

python - 在 Matplotlib 中如何防止图像出现在屏幕上? Python

c++ - boost::function 和 boost::bind 很酷,但是 boost::lambda 真正酷的是什么?

c++ - Qt 找不到子项目中的文件

python - 有没有办法让 python str.partition 忽略大小写?

python - 了解类型错误: '<' not supported between instances of 'Example' and 'Example'

c# - 捕捉引擎ExecutionException

c++ - 如何使用可变参数模板处理模板特化?

c++ - 在 Qt 资源系统 (qt 5.0.2) 中读取和写入文件