![](/img/trans.png)
[英]How to continuously communicate between Java and Python using TCP socket
[英]Communicate data between C and Python apps running continuously
有沒有辦法在連續運行的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中完成此操作,但是統一的單一實現會更好。
您有幾種選擇
您必須設計一種基於行的格式,從stdin中讀取一行,並打印您想要傳達給父進程的內容。
參見下面的例子
在這方面,我建議使用zmq。 它是跨平台的,具有很多功能。
因此,Python中的一些代碼展示了stdin / stdout通信的總體思路
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()
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它必須殺死自己。 這些過程可能會長時間運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.