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?
p.stdoutis a io.BytesIO object; syntactically you can read however you want from it as if it's a file. You might also want to look into thebufsizeargument depending on your need.