Inter-process communication between python and c++

Viewed 2050

I have a python script to process data (as part of a bigger framework), and a c++ script to gather data from an instrument. The c++ code continuously gathers then emits data via cout.

The programs need to talk to each other such:

  • Python -> Calls c++ script which start gathering
  • (Waits for x amount time)
  • Python -> Sends command to c++ script to stop gathering and emit data
  • c++ -> Receives command and acts on it
  • Python -> Receives data

I'm struggling with the last step, I feel like an interrupt is the best way to do it but I'm probably wrong? Here's what I have at the moment:

(Python)

p = Popen("C++Script.exe", stdin=PIPE, stdout=PIPE, bufsize=1, shell=True)

# Wait for stuff to happen
# Send command to change read_flag to False in c++ script

for line in iter(p.stdout.readline, ''):
    line = str(line)  # Contains data to be parsed, obtained from cout
    # Do stuff..

.

(c++ main)

...
BOOL read_flag = TRUE;
thread t1{ interrupt, &read_flag };

float Temp;
vector <float> OutData;

//Data read and stored in vector
for (int i = 1; read_flag == TRUE; i++) 
{
    Temp = Get_Single_Measurement();
    OutData.push_back(Temp); 
}

//Data read out in one go
for (int i = 0; i < OutData.size(); i++)
{
    cout << OutData[i] << endl;  //Picked up by python code
}

t1.join();
...

(c++ interrupt)

void interrupt(BOOL *read_flag)
{
    // Listen for Python command to interrupt reading
    *read_flag = FALSE;
}

If anyone can point me on the write track it'd be really helpful, happy to adopt any solution that works.

Thanks!!

0 Answers
Related