input to C++ executable python subprocess

2024/10/9 14:22:39

I have a C++ executable which has the following lines of code in it

/* Do some calculations */
.
.
for (int i=0; i<someNumber; i++){int inputData;std::cin >> inputData;std::cout<<"The data sent from Python is :: "<<inputData<<std::endl;../* Do some more calculations with inputData */
}

and this is called in a loop. I want to call this executable in python subprocess like

p = Popen(['./executable'], shell=True, stdout=PIPE, stderr=PIPE, stdin=PIPE)

I could get the output from the executable using

p.server.stdout.read()

But I am not able to send data (integers) from python using

p.stdin.write(b'35')

Since cin is called in a loop, the stdin.write should also be called multiple times (in a loop). Is this above possible .. ?

Any hints and suggestion how I could do it ? Thanks in advance.

Answer

Here's minimalistic example of how to call a C++ executable from Python, and communicate with it from Python.

1) Note that you must add \n when writing to input stream (i.e. stdin) of the subprocess (just like you would hit Rtn if running the program manually).

2) Also note the flushing of the streams, so that the receiving program doesn't get stuck waiting for the whole buffer to fill before printing the result.

3) And if running Python 3, be sure to convert the streaming value from string to bytes (see https://stackoverflow.com/a/5471351/1510289).

Python:

from subprocess import Popen, PIPEp = Popen(['a.out'], shell=True, stdout=PIPE, stdin=PIPE)
for ii in range(10):value = str(ii) + '\n'#value = bytes(value, 'UTF-8')  # Needed in Python 3.p.stdin.write(value)p.stdin.flush()result = p.stdout.readline().strip()print(result)

C++:

#include <iostream>int main(){for( int ii=0; ii<10; ++ii ){int input;std::cin >> input;std::cout << input*2 << std::endl;std::cout.flush();}
}

Output of running Python:

0
2
4
6
8
10
12
14
16
18
https://en.xdnf.cn/q/70011.html

Related Q&A

pandas extrapolation of polynomial

Interpolating is easy in pandas using df.interpolate() is there a method in pandas that with the same elegance do something like extrapolate. I know my extrapolation is fitted to a second degree polyno…

Speed-up a single task using multi-processing or threading

Is it possible to speed up a single task using multi-processing/threading? My gut feeling is that the answer is no. Here is an example of what I mean by a "single task":for i in range(max):p…

Full outer join of two or more data frames

Given the following three Pandas data frames, I need to merge them similar to an SQL full outer join. Note that the key is multi-index type_N and id_N with N = 1,2,3:import pandas as pdraw_data = {type…

How can I add a level to a MultiIndex?

index = [np.array([foo, foo, qux]),np.array([a, b, a])] data = np.random.randn(3, 2) columns = ["X", "Y"] df = pd.DataFrame(data, index=index, columns=columns) df.index.names = [&qu…

decoupled frontend and backend with Django, webpack, reactjs, react-router

I am trying to decouple my frontend and my backend in my project. My frontend is made up of reactjs and routing will be done with react-router, My backend if made form Django and I plan to use the fron…

Map colors in image to closest member of a list of colors, in Python

I have a list of 19 colors, which is a numpy array of size (19,3):colors = np.array([[0, 0, 0], [0, 0, 255], [255, 0, 0], [150, 30, 150], [255, 65, 255], [150, 80, 0], [170, 120, 65], [125, 125,…

Storing a file in the clipboard in python

Is there a way to use the win32clipboard module to store a reference to a file in the windows clipboard in python. My goal is to paste an image in a way that allows transparency. If I drag and drop a…

retrieve intermediate features from a pipeline in Scikit (Python)

I am using a pipeline very similar to the one given in this example : >>> text_clf = Pipeline([(vect, CountVectorizer()), ... (tfidf, TfidfTransformer()), ... …

Any way to do integer division in sympy?

I have a very long expression that I think can be simplified, and I thought sympy would be the perfect way to do it. Unfortunately the formula relies on a couple of integer divides, and I cant find any…

Scrapy LinkExtractor - Limit the number of pages crawled per URL

I am trying to limit the number of crawled pages per URL in a CrawlSpider in Scrapy. I have a list of start_urls and I want to set a limit on the numbers pages are being crawled in each URL. Once the l…