在连续运行的C和Python应用程序之间传递数据

有没有办法在连续运行的C程序和连续运行的Python程序之间传递数据? C程序首先启动至关重要。

到目前为止,我有(对于C方):

void run_cmd(char *cmd[]) { int parentID = getpid(); char str[1*sizeof(double)]; sprintf(str, "%d", parentID); char* name_with_extension; name_with_extension = malloc(2+strlen(cmd[1])+1*sizeof(int)+1); strcat(name_with_extension, cmd[1]); strcat(name_with_extension, " "); strcat(name_with_extension, str); pid_t pid; char *argv[] = {"sh", "-c", name_with_extension, NULL}; int status; //printf("Run command: %s\n", cmd); status = posix_spawn(&pid, "/bin/sh", NULL, NULL, argv, environ); if (status == 0) { //printf("Child pid: %i\n", pid); //printf("My process ID : %d\n", getpid()); //if (waitpid(pid, &status, 0) != -1) { // printf("Child exited with status %i\n", status); //} else { // perror("waitpid"); //} //part below is not tested and will probably not work int myout[2]; pipe(myout); int status; int ch; do { if (read(myout[0], &ch, 1)>0){ write(1, &ch, 1); } waitpid(pid, &status, WNOHANG); } while (!WIFEXITED(status) && !WIFSIGNALED(status)); } } 

对于Python,我现在只能使用以下参数列表:

 print 'Arguments ', str(sys.argv) 

正如我从文档中所理解的那样, subprocess.Popen不是一种可行的方法,因为它创建了一个我不想要的新进程。

在Python(或反向)中嵌入 C不是一个选项,因为代码太大了。

我认为使用进程ID和可能的套接字之间传递数据,但不确定并需要一些建议。

目标是在Windows中实现这一点,但统一的单一实现会更好。

你有几个选择

  1. 通过stdin传递数据并输出到stdout。

您必须设计基于行的格式,从stdin读取一行并打印您要与父进程通信的内容。

请参阅下面的示例

  1. 使用IPC机制进行过程通信

在这个我建议使用zmq。 它是跨平台的,具有相当多的function。

所以,python中的一些代码显示了stdin / stdout通信的一般概念

P1(孩子)

 import sys import time i=0 while True: line = sys.stdin.readline().strip() if not line: time.sleep(0.5) if line=="ping": sys.stdout.write("pong\n") sys.stdout.flush() i+= 1 if i > 10: sys.stdout.write("exit\n") sys.stdout.flush() 

P2(主人)

 import subprocess p = subprocess.Popen(['python', './p1.py'],stdout=subprocess.PIPE, stdin=subprocess.PIPE) while True: p.stdin.write("ping\n") p.stdin.flush() ret = p.stdout.readline().strip() print ret if ret=='exit': exit(0) 

P2开始P1,他们做10次乒乓,p1通知p2它必须自杀。 这些过程可以长期运行。