I have used the following code to pass input to cpp program which reads input and prints it.
from subprocess import Popen, PIPE
p = Popen(['a.exe'], 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)
Following was the output of python
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
EDIT: Following is the code for cpp file
#include<iostream>
using namespace std;
int main()
{
int a[10];
for(int i=0;i<10;i++)
{
cin>>a[i];
cout<<a[i];
std::cout.flush();
}
return 0;
}
I tried code on Linux and I had two problems
in Python I had to use full path to a.exe
to run it
in CPP I had to add << '\\n'
because it sends text without \\n
and p.stdout.readline()
is waiting for \\n
Without full path I saw many b''
(and message "... not found"
in first line)
Without << '\\n'
script freezed because readline()
was waiting for \\n
EDIT: I forgot: I had to add p.stdin.flush()
.
EDIT: as @Sugar suggested in comment - use std::endl
instead of "\\n"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.