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 
#include 

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'))

你可能感兴趣的:(python,C)