5

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!!

JohnJos
  • 101
  • 1
  • 6
  • haven't studied your issue in detail but I think pexpect can do what you want https://pexpect.readthedocs.io/en/stable/ – Irmen de Jong Sep 26 '17 at 08:38
  • There are several ways to do [inter process communication](https://en.wikipedia.org/wiki/Inter-process_communication). Each has some advantages and disadvantages. It seems to me that signals may be what you are looking for: simply send SIGINT to the subprocess from Python. Also possible solutions are OS dependent. – freakish Sep 26 '17 at 08:39
  • 1
    Have you considered sockets? As long as both processes are on the same machines you can use address 127.0.0.1, but this solution can be easily expanded to running python script on one machine and C++ app on another. – Darth Hunterix Sep 26 '17 at 08:42

0 Answers0