使用python的子进程同时捕获并输出stderr

(目前使用python 3.2)

我需要能够:

  • 使用子进程运行一个命令
  • 该命令的stdout / stderr都需要实时打印到终端(无论它们是在stdout还是stderr上出现都没关系
  • 同时,我需要一种方法来知道命令是否向stderr打印了任何内容(最好是打印的内容)。
  • 我玩过子流程管道以及在bash中做奇怪的管道重定向,以及使用tee ,但是至今还没有发现任何可行的东西。 这是可能的吗?


    我的解决方案

    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())
    

    尝试这样的事情:

    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
    

    在python2中,你可以很容易地使用popen3来捕获stderr,如下所示:

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

    但python3似乎没有这样的功能。 如果您找不到解决方法,请直接使用subprocess.Popen ,如下所述:http://www.saltycrane.com/blog/2009/10/how-capture-stdout-in-real-time-python/

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

    上一篇: Catching and outputting stderr at the same time with python's subprocess

    下一篇: Pipe subprocess standard output to a variable