0

I want to use subprocess to call other py files and get output. The colors they output are the same, How can i distinguish between stdout and stderr in subprocess?

run.py

def run():
    for i in range(3):
        print('Processing {}.'.format(i))
        time.sleep(1)
    print(1/0)
run()

main.py

import subprocess
import sys

def byte2str(b):
    return str(b, encoding='utf-8')

if __name__ == '__main__':
    cmd = [sys.executable, 'temp/run.py']
    p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    while p.poll() is None:
        line = p.stdout.readline()
        if line:
            print(byte2str(line), end='')
Alex
  • 150
  • 9
  • I don't recommend trying. If you split stdout and stderr into two separate streams, you lose any ability to get their canonical ordering. (This isn't a Python thing, it's a limitations-of-UNIX-file-descriptor-semantics thing). – Charles Duffy Nov 08 '19 at 03:18
  • ...however, if you *wanted* to, you'd need to change `stderr=subprocess.STDOUT` to instead be `stderr=subprocess.PIPE`, and have a separate process reading from `p.stderr`, and writing everything that's read from it out in a different color. Again, though, that'll break your ordering -- if you have, say, `STDOUT:A1`; `STDERR:B1`, `STDOUT:A2`, `STDERR:B2` events happening, there's no guarantee whatsoever that they won't become `STDERR:B1`, `STDERR:B2`, `STDOUT:A1`, `STDOUT:A2`. – Charles Duffy Nov 08 '19 at 03:19
  • See [Separately redirecting and recombining stdout and stderr without losing ordering](https://stackoverflow.com/questions/45760692/separately-redirecting-and-recombining-stderr-stdout-without-losing-ordering) for some background. – Charles Duffy Nov 08 '19 at 03:20
  • Thanks for comment , It was completely beyond me.>_ – Alex Nov 08 '19 at 05:50

0 Answers0