Can you fool isatty AND log stdout and stderr separately?

前端 未结 4 1759
悲&欢浪女
悲&欢浪女 2020-12-28 12:55

Problem

So you want to log the stdout and stderr (separately) of a process or subprocess, without the output being different from what you\'d see in the terminal i

4条回答
  •  悲&欢浪女
    2020-12-28 13:08

    You can always allocate Pseudo-TTY, that's what screen does.

    In Python you'd access it using pty.openpty()

    This "master" code passes your test:

    import subprocess, pty, os
    
    m, s = pty.openpty()
    fm = os.fdopen(m, "rw")
    p = subprocess.Popen(["python2", "test.py"], stdin=s, stdout=s, stderr=s)
    p.communicate()
    os.close(s)
    print fm.read()
    

    Of course if you want to distinguish between stdin/out/err, your "slave" process will see different PYT names:

    inp = pty.openpty()
    oup = pty.openpty()
    erp = pty.openpty()
    
    subprocess.Popen([command, args], stdin=inp[1], stdout=uop[1], stderr=erp[1])
    

提交回复
热议问题