w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Get output from a program with the user input that program takes

You need select to read from more than one source at the same time (in your case stdin and the output of the child process).

import select

string = ''
while True:
  r, w, e = select.select([ child.stdout, sys.stdin ], [], [])
  if child.stdout in r:
    string += child.stdout.read()
  if sys.stdin in r:
    typed = sys.stdin.read()
    child.stdin.write(typed)
    string += typed

You will still need to find a proper breaking condition to leave that loop. But you probably get the idea already.

I want to give a warning at this point: Processes writing into pipes typically buffer until the latest possible moment; you might not expect this because when testing the same program from the command line (in a terminal) typically only lines get buffered. This is due to performance considerations. When writing to a terminal, typically a user expects to see the output as soon as possible. When writing to a pipe, typically a reading process is happy to be given larger chunks in order to sleep longer before they arrive.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.