[PYTHON] I can't enter standard in Subprocess ...

problem

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

solution

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

I can't enter standard in Subprocess ...
I can't enter characters in the text area! ?? !! ?? !! !! ??
I can't install scikit-learn in Python
I can't debug python scripts in Eclipse
I can't get the element in Selenium!
Why can't I install matplotlib in python! !!
Get standard output in real time with Python subprocess
I read PEP 585 (Type Hinting Generics In Standard Collections)
I can't install Anaconda!
I can't manipulate iframes in a page with Selenium
[Note] I can't call the installed module in jupyter
I can't use the darknet command in Google Colaboratory!
I can't log in to the admin page with Django3
I wrote python in Japanese
Write standard input in code
I read "Linux standard textbook"!
Transposed matrix in Python standard
I can't search with # google-map. ..
I understand Python in Japanese!
What I learned in Python
I participated in AtCoder (ABC158)
Read the standard output of a subprocess line by line in Python
I get a can't set attribute when using @property in python
I can't import modules in the parent directory even with sys.path.append ('..')