Say I have a Python 3 program like this:
print("Addition program")
num1 = int(input(">>> "))
num2 = int(input(">>> "))
print(num1 + num2)
I'm running it in the terminal and displaying the output with:
import subprocess
def run_command(command):
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return iter(p.stdout.readline, b'')
for i in run_command(["python", "file.py"]): print(i)
How can I pass inputs to the program, either in the command itself, or while its running? Thanks in advance!
Edit:
I found a solution that allows me to use pipes stdin and stdout. So I can pass input with stdin.write(b'. . . .'). However, once I use this command, I have to use the .communicate() method to obtain output or else the process hangs. Right now my code is:
import subprocess
from subprocess import PIPE
import shlex
p=subprocess.Popen(["python", "file.py"], stdin=PIPE, stdout=PIPE)
one_line_output = p.stdout.readline()
print(one_line_output.decode(), end = "")
p.stdin.write(b'a line\n')
one_line_output = p.communicate()[0] # end the process
print(one_line_output.decode(), end = "")
one_line_output = p.stdout.readline()
print(one_line_output.decode(), end = "")
'''
When this line of code runs, it raises an error:
Traceback (most recent call last):
File ". . . .", line 27, in <module>
one_line_output = p.stdout.readline()
ValueError: readline of closed file
'''
Is there a way I can continue to pass inputs and read lines?