C中的popen函数和Python中Popen方法

mingw中popen的声明如下(stdio.h):

_CRTIMP __cdecl __MINGW_NOTHROW  FILE *  popen (const char *, const char *);
_CRTIMP __cdecl __MINGW_NOTHROW  int     pclose (FILE *);

调用例子

#include <stdio.h>
#include <stdlib.h>

char buf[10240] = {0};

int  main(void)
{
    FILE *fp = NULL;

    fp = popen("CJSON.exe","r");  //r for read, read from CJSON.stdout->fp
                                    //w for write,write cmd from fp to CJSON.stdin
    if(!fp)
    {
        perror("popen");
        exit(EXIT_FAILURE);
    }
    fread(buf, 10240, 1, fp);
    printf("%s\n",buf);
    pclose(fp);

}

Python中Popen方法完成上述功能更方便简洁

import subprocess
p = subprocess.Popen(['JSON.exe'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
    output,err=p.communicate()
except TimeoutExpired:
    p.kill()
    outs, errs = p.communicate()


print(output.decode('utf-8'))

猜你喜欢

转载自blog.csdn.net/ambercctv/article/details/80035848