4

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Keatinge
  • 4,330
  • 6
  • 25
  • 44
  • Does this answer your question? [Why doesn't print output show up immediately in the terminal when there is no newline at the end?](https://stackoverflow.com/questions/25897335/why-doesnt-print-output-show-up-immediately-in-the-terminal-when-there-is-no-ne) – Tomerikoo Jan 03 '23 at 11:17

1 Answers1

5

Use:

print(char, end="", flush=True)
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251