proc.stdout already a string in your case, run print(type(proc.stdout)) to make sure. It contains all the subprocess output - subprocess.run() not returned until the child process is dead.
for text_line in proc.stdout: false: for char in text_string lists characters (Unicode code pages) in Python, not in strings. To get the lines, call:
lines = result.stdout.splitlines()
The result may differ from .split('\n') if there are Unicode lines in the line.
If you want to read the output of line by line (to avoid running out of memory for long processes):
from subrocess import Popen, PIPE with Popen(command, stdout=PIPE, universal_newlines=True) as process: for line in process.stdout: do_something_with(line)
Note: process.stdout is a file-like object in this case. Popen() does not Popen() for the process to complete - Popen() returns immediately after starting the child process. process is a subprocess.Popen instance, not a CompletedProcess here.
If you only need to count the number of lines (terminated by b'\n' ), for example wc -l :
from functools import partial with Popen(command, stdout=PIPE) as process: read_chunk = partial(process.stdout.read, 1 << 13) line_count = sum(chunk.count(b'\n') for chunk in iter(read_chunk, b''))
See Why are reading lines from stdin much slower in C ++ than Python?
source share