Python doesn't print anything when using end parameter with print from a subprocess pipe

Question:

I’m trying to run a python script from within another python script using subprocesses. (No importing, I want this to work for any program, not just python)

Here is the first file: getting_input.py

name = input("Sample input prompt: ")

Here is the file I am using to run any shell command: test.py

import subprocess

proc = subprocess.Popen("python getting_input.py", stdout=subprocess.PIPE)
for char in iter(lambda: proc.stdout.read(1).decode('utf-8'), ''):
    print(char)  # This actually works, printing every character on a new line

But when the only thing I change is add end="" to my print statement absolutely nothing gets printed.

import subprocess

proc = subprocess.Popen("python getting_input.py", stdout=subprocess.PIPE)
for char in iter(lambda: proc.stdout.read(1).decode('utf-8'), ''):
    print(char, end="")  # This doesn't work, nothing at all gets printed... ????

I am assuming this is some sort of buffering issue, but even when I run it with python -u test.py and inside it use python -u getting_input.py I still see no output. Any ideas?

Asked By: Keatinge

||

Answers:

Use:

print(char, end="", flush=True)
Answered By: Mark Tolonen