I am writing a small python application which executes scala commands. A user can insert the command through the STDIN and then the python app forwards them to the scala interpreter. Once the command is executed, the app shows the result of the operation.
The idea is to use Popen
to create a pipe by which I can send commands and read results. The idea is quite simple, but it doesn't work. What I don't understand is, why the sys.stdin
doesn't work anymore after the pipe is opened. This makes impossible to read commands in python.
This is the code I am using:
import sys
from subprocess import Popen, PIPE
with Popen(["scala"], stdout=PIPE, stdin=PIPE, bufsize=0, universal_newlines=True) as scala:
while True:
print("Enter scala command >>> ", end="")
sys.stdout.flush()
command = input()
scala.stdin.write(command)
scala.stdin.flush()
print(scala.stdout.readline())
You need to read all the lines from when the scala starts then input the command with a new line and get the two lines of output after:
An example run:
To get it to work from bash running it with unbuffer seems to sort out the output issues:
If you are using Mac Os x, you should probably use :
From bash:
More info regarding shell buffer issues: