Catching and outputting stderr at the same time with python's subprocess

(Using python 3.2 currently)

I need to be able to:

  • Run a command using subprocess
  • Both stdout/stderr of that command need be printed to the terminal in real-time (it doesn't matter if they both come out on stdout or stderr or whatever
  • At the same time, I need a way to know if the command printed anything to stderr (and preferably what it printed).
  • I've played around with subprocess pipes as well as doing strange pipe redirects in bash, as well as using tee , but as of yet haven't found anything that would work. Is this something that's possible?


    我的解决方案

    import subprocess
    
    process = subprocess.Popen("my command", shell=True,
                               stdout=None, # print to terminal
                               stderr=subprocess.PIPE)
    duplicator = subprocess.Popen("tee /dev/stderr", shell=True, # duplicate input stream
                                  stdin=process.stderr, 
                                  stdout=subprocess.PIPE, # catch error stream of first process
                                  stderr=None) # print to terminal
    error_stream = duplicator.stdout
    print('error_stream.read() = ' + error_stream.read())
    

    Try something like this:

    import os
    
    cmd = 'for i in 1 2 3 4 5; do sleep 5; echo $i; done'
    p = os.popen(cmd)
    
    while True:
        output = p.readline()
        print(output)
        if not output: break
    

    In python2 you can catch stderr easily as well by using popen3 like this:

    i, o, err = os.popen3(cmd)
    

    but there seem to be no such function in python3. If you don find the way around this, try using subprocess.Popen directly, as described here: http://www.saltycrane.com/blog/2009/10/how-capture-stdout-in-real-time-python/

    链接地址: http://www.djcxy.com/p/77146.html

    上一篇: 来自subprocess命令的实时输出

    下一篇: 使用python的子进程同时捕获并输出stderr