There is a standard python library called subprocess. This is a substitute that can execute multiple executable files at the same time, but this time it was jammed with standard input to the executable file.
For example, suppose you create the following C ++ file and make it an exe.
sample.cpp
include <iostream>
using namespace std;
int main(){
while(true){
int a;
cout << "input"
cin >>a;
cout << a * 2;
return 0;
}
}
Well, I just receive the number and display the number that is doubled, but I want to keep running this with while and run it from python without starting it one by one.
I didn't know what to do when doing this ...
I made the previous code executable as sample.exe. Then the code below worked.
import subprocess
#Universal because it is troublesome to exchange with bytes_newline true
sample = subprocess.Popen("sample.exe",
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
if sample.stdout.readline() == "input:\n": #The text to be read must include line breaks.
sample.stdin.write("20\n") #Line breaks are required for input
sample.stdin.flush() #Since the input is in the buffered state, it is the first input here.
This works. I wrote the important parts in the code, so check them together. It's really difficult. subprocess
Recommended Posts