Python subprocess update its lines (\ r) - i need every update

As suggested in the answer to my question " Python: Run a terminal program and parse its output while it is running " I use a subprocess construct to communicate with the program

server = subprocess.Popen(["meteor", "--port",  port], stdout=subprocess.PIPE)

for line in iter(server.stdout.readline, ""):
  # Do something for example
  print(line)

      

The problem is this: the subprocess (server) does not end each line with a newline directly, as it puts (x2) at the end of the line when the message is duplicated.

But I want to be responsive to every row update. So I want to handle \r

how \n

, not just looping through the ready-made lines, I want to iterate over the available line until the next "pause", which is \r

or \n

or another line break to receive information directly when it appears, not just when the server sends \n

. How can i do this?

+3


source to share


1 answer


perhaps if you try to use a non-blocking connection with a channel. then read the stream just like socket connection (while (true) loop) ... hopefully this will point you in the right direction.

from fcntl import fcntl, F_GETFL, F_SETFL
from os import O_NONBLOCK, read

server = subprocess.Popen(["meteor", "--port",  port], stdout=subprocess.PIPE)
flags = fcntl(server.stdout, F_GETFL) # get current p.stdout flags
fcntl(server.stdout, F_SETFL, flags | O_NONBLOCK)

while True:
    print read(server.stdout.fileno(), 1024),

      



you will need to add error handling for dropped connection or more data.

+4


source







All Articles