How to read stdout subprocess using another line break delimiter

I think I can use from the answer of J.F. Sebastian in another thread to read from the subprocess line by line using the line buffer

p = Popen(["command", "args"], stdout=PIPE, bufsize=1)
with p.stdout:
    for line in iter(p.stdout.readline, b''):
        print(line, end='\n')

The problem I'm trying to solve is that my output does not have line breaks, but uses special characters (for example, "#") to indicate completion, which I want to consider as line breaks when printing. A.

+4
source share
1 answer

You can read char at a time to check for delimiters:

p = Popen(["command", "args"], stdout=PIPE, universal_newlines=True)
tmp = ""
delims = {"#", "!"}
for ch in iter(lambda: p.stdout.read(1), ""):
    if ch in delims:
        print(tmp)
        tmp = ""
    else:
        tmp += ch

Not the nicest solution, but if you have multiple delimiters, I don’t see many other ways to do this.

+2

All Articles