Skip to content Skip to sidebar Skip to footer

Communicate Data Between C And Python Apps Running Continuously

Is there a way to pass data between continuously running C program and continuously running Python program? It is crucial that C program starts first. So far I have (for C side): v

Solution 1:

You have a couple of options

  1. Pass data through stdin and output to stdout.

You'll have to devise a line-based format, read a line from stdin and print what you want to communicate to parent process.

See the example below

  1. Use an IPC mechanism for process communication

In this I'd propose using zmq. It's cross-platform and has quite a few features.

So, a bit of code in python showing the general idea with stdin/stdout communication

P1 (the child)

import sys                             
import time                            
i=0while True:                            
    line = sys.stdin.readline().strip()
    ifnot line:                       
        time.sleep(0.5)                

    if line=="ping":                   
        sys.stdout.write("pong\n")     
        sys.stdout.flush()             
        i+= 1if i > 10:                         
        sys.stdout.write("exit\n")     
        sys.stdout.flush()    

P2 (the master)

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 starts P1, they do 10 ping-pongs and p1 notifies p2 that it must kill itself. The processes can be long running.

Post a Comment for "Communicate Data Between C And Python Apps Running Continuously"