popen函数为何读取不到内容?

#include <cstdio>
#include <cstring>
#include <string>

using namespace std;

#define SPLIT_SIZE 1048576
#define BUFFER_SIZE 1000

int main(int argc, char const *argv[])
{
    printf("rcpkg - resource packager for C/C++(GNU), created by DL.\n");
    // check commands
    if (argc < 4)
    {
        printf("Usage: rcpkg input_file_name output_library_name output_directory.\n");
        return 0;
    }
    // check gcc
    // FILE* gcc = popen("ruby -v", "r");
    FILE* gcc = popen("python --version", "r");
    if (!gcc)
    {
        printf("Cannot execute command.\n");
        return 0;
    }
    char buffer[BUFFER_SIZE];
    string res = "";
    while(memset(buffer, 0, BUFFER_SIZE - 1), fgets(buffer, BUFFER_SIZE - 1, gcc) != 0)
        res += buffer;
    printf("========\n%s\n========\n", res.c_str());
    pclose(gcc);
    // open file
    FILE* input = fopen(argv[1], "rb");
    if (!input)
    {
        printf("Cannot open file %s.\n", argv[1]);
        return 0;
    }
    fseek(input, 0, SEEK_END);
    auto fs = ftell(input);
    fseek(input, 0, SEEK_SET);
    printf(">\tSize of file %s is %ld.\n", argv[1], fs);
    fclose(input);
    return 0;
}

用popen执行"python --version"这个命令,结果用fgets读取不到结果,然而把命令改为"ruby -v"就一切正常,这是为什么啊?
图片描述

阅读 5.7k
1 个回答

因为 popen() 只能捕获 stdout(标准输出), 忽略了 stderr.

而 python2.7 恰好往 stderr 输出版本信息, 见
https://github.com/python/cpy...

    if (version) {
        fprintf(stderr, "Python %s\n", PY_VERSION);
        return 0;
    }

要从 popen() 中捕获 stderr, 可以使用 shell 的重定向功能, 将 stderr 改向 stdout, 如

popen("python2 --version 2>&1")

python3.7 的版本信息写往 stdout, 与 python2.7 不同.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题