0

I am trying to create a python script that will send lines into a cpp file running on a while loop and printing the lines received into the console.

test.py

#test.py
import subprocess

p = subprocess.Popen('./stdin.out',bufsize=1,stdin=subprocess.PIPE,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, universal_newlines=True)

p.stdin.write('hello world\n')
p.stdin.write('hell world\n')
p.stdin.write('hel world\n')

p.terminate()

stdin.cpp

//stdin.cpp
#include <iostream>

int main(){
  std::string line;
  std::cout << "Hello World! from C++" << std::endl;
  while (getline(std::cin, line)) {
    std::cout <<"Received from python:" << line << std::endl;
  }
  return 0;
}

Is this achievable?

4
  • 1
    What went wrong? Instead of p.terminate(), you may want p.stdin.close() follwed by p.wait(). Commented Nov 23, 2022 at 15:48
  • It doesnt send anything to the cpp bin and does not print anything to the console Commented Nov 23, 2022 at 16:15
  • I think you terminated the cpp program before it had a chance to do anything. Commented Nov 23, 2022 at 16:17
  • How to not terminate the program. I have tried it with also a while true at the cpp but I was not even able to print anything Commented Nov 23, 2022 at 16:54

1 Answer 1

1

You have two problems. The first is that the python script terminates the subprocess before it has a chance to run. The second is that you pipe stdout and err to DEVNULL, so even if it did run, you wouldn't see anything. Normally, when you are done communicating with a subprocess, you close stdin. The subprocess can read stdin at its leasure and discover the close naturally at the end of input. Then wait for it to exit.

#!/usr/bin/env python3
#test.py
import subprocess

p = subprocess.Popen('./wc',bufsize=1,stdin=subprocess.PIPE, universal_newlines=True)

p.stdin.write('hello world\n')
p.stdin.write('hell world\n')
p.stdin.write('hel world\n')
p.stdin.close()
p.wait()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.