0

I am integrating a c++ code with a python program. I have a python script that in loop waits for input. The problem is that I have to pass this input from a c++ program and read the result. I cannot use files! For every input I have to return a value to the c++ program without stopping the script. The python program must be running because in its initialization generates a data structure which I cannot build every time (quite expensive).

This is the python script prototype:

while (true):
  input_string = input()
  result = my_function(input_string)
  return_result(result)

I have a simple function my_function which computes a result (string) and I have to return this result to the calling c++ program (through the function return_result).

I am looking for a solution specifically to send the input from a c++ program to a running python script for further processing.

Melebius
  • 4,692
  • 3
  • 32
  • 43
Riky
  • 1
  • 1
  • 7
    You must provide a [mcve] – eyllanesc Dec 14 '17 at 15:57
  • Isn’t a subprocess suitable for you? https://stackoverflow.com/questions/89228/calling-an-external-command-in-python/89243 – Melebius Dec 14 '17 at 15:58
  • I cannot restart the python script every time because I use a data structure and I did not want to build it every time. Otherwise from c++ a simple system will be fine. I want the python program running and on-demand the c++ program pass its input. – Riky Dec 14 '17 at 16:08
  • You run some process (which happens to be a python script) from c++, using OS specific means to get a handle to its stdin. Then you stream text to its stdin through that handle. The python code is irrelevant -- it is just any process that takes input from stdin. – Kenny Ostrom Dec 14 '17 at 16:13
  • @Riky what is your OS? – eyllanesc Dec 14 '17 at 16:14
  • When you say "the already running python program" that poses some problems. You may need to be more familiar with your operating system. I am assuming that one program launches the other, and has handles to both stdin and stdout. Also see Melebius's comment -- it may be easier to just do it all in python. – Kenny Ostrom Dec 14 '17 at 16:18
  • @KennyOstrom the problem is that I am integrating my python procedure with a c++ code (not written by me), so unfortunately I cannot do all in python. About one process running the other, you are saying that from c++ I run my python program and I get the handle to the stdin and stdout? This should be great. How do I get the handlers? – Riky Dec 14 '17 at 16:33
  • @eyllanesc I am using linux over ubuntu 16.04.3 – Riky Dec 14 '17 at 16:36
  • Look for example code with popen, or fork and pipe. – Kenny Ostrom Dec 15 '17 at 19:28
  • @Riky “I am integrating my python procedure with a c++ code” Have you access to the C++ source code? Couldn’t you create a Python module implemented in C++? [SWIG](http://www.swig.org/) can help with that. – Melebius Dec 18 '17 at 09:37

0 Answers0