Medita Inc.
Medita Inc.

Reputation: 57

How to get realtime Python subprocess output?

Program that I'm trying to run using shell command, outputs one word per second. I'm trying to execute a shell command within Python script and get realtime output on each word that is outputed. All the other solutions I found online, don't actually print the realtime output but rather one finished line at the time. I want to get the real realtime output where each word is printed out in realtime rather than each line. This is the code that I've tried:

cmd=['slowprogram','-m', '15', '-l', '50']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print(line),
p.stdout.close()
p.wait()

It waits until one line is finished and the prints it. Is there a way to get updates on and print each word in a line, in realtime?

UPDATE:

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    for word in iter(line):
      print(word)
p.stdout.close()
p.wait()

returns a bunch of numbers for some reason...:

111
117
108
100
32
104
97
118
101
32
115
97

How can I get each word from the line?

Upvotes: 0

Views: 3781

Answers (1)

YiFei
YiFei

Reputation: 1802

This is one way to do it and it worked for me in a Linux shell. It uses an unbuffered IO object and prints out one character at a time. I'm quite sure there are better ways since I'm not an expert on either subprocess or event handling. You may also want to look into asyncio.

with subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=0) as p:
    char = p.stdout.read(1)
    while char != b'':
        print(char.decode('UTF-8'), end='', flush=True)
        char = p.stdout.read(1)

Upvotes: 2

Related Questions