之前写了一个python程序,基本功能是检测表计读数,然后输出。当时认为python写比较简单,而且正好在学习python,于是就写了......

后来发现python打包成exe然后打开实在是太慢了,等待时间超长,而且exe文件很大,才发现python对程序发布很不友好,平时写些小程序也就罢了,真到正式场合有点...emmm掉链子,正好客户那边用的是c++,于是思考如何用c++调用python。

第一个思路是使用文件来传递数据,c++生成数据写入文件,然后python读取,生成结果之后再写入文件让c++读取,可是问题一是读取的时机需要把握,因为程序的运行需要时间,如何去读文件是一个问题,问题二是太麻烦了,感觉不是一个解决问题的最佳办法。

于是搜索比较优雅的方式,找到了这个函数:popen()

popen() 函数通过创建一个管道,调用 fork 产生一个子进程,执行一个 shell 以运行命令来开启一个进程。这个进程必须由 pclose() 函数关闭,而不是 fclose() 函数。pclose() 函数关闭标准 I/O 流,等待命令执行结束,然后返回 shell 的终止状态。如果 shell 不能被执行,则 pclose() 返回的终止状态与 shell 已执行 exit 一样。

函数定义如下:

FILE * popen ( const char * command , const char * type );
int pclose ( FILE * stream ); 

其中:

command 参数就是我们想要运行的cmd命令。在本例中,为python pointer.py(运行pointer.py程序)

type参数只能是读或者写中的一种,得到的返回值(标准 I/O 流)也具有和 type 相应的只读或只写类型。如果 type 是 "r" 则文件指针连接到 command 的标准输出;如果 type 是 "w" 则文件指针连接到 command 的标准输入。

需要注意的是:popen 的返回值是个标准 I/O 流,必须由 pclose 来终止。

下面为程序代码

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

using namespace std;

int main(int argc, char *argv[])
{

	FILE *fp;
	char result[100];
	string imgpath = "image.jpg";
	string cmd = "python pointer.py ";
	cmd += imgpath;
	//cout << cmd << endl;

	/* Open the command for reading. */
	fp = _popen(cmd.c_str(), "r");
	if (fp == NULL) {
		printf("Failed to run command\n");
		exit(1);
	}

	/* Read the output a line at a time - output it. */
	while (fgets(result, sizeof(result) - 1, fp) != NULL) {
		printf("%s", result);
	}

	_pclose(fp);

	getchar();
	return 0;
}

结果由

fgets(result, sizeof(result) - 1, fp  )

这一句得到

注意:在vs2015中,使用的是_popen()和_pclose()

运行结果:



image.jpg:


更多推荐

c++调用python程序(使用popen)