【问题标题】:Catching and outputting stderr at the same time with python's subprocess用python的子进程同时捕获和输出stderr
【发布时间】:2012-10-04 20:48:21
【问题描述】:

(目前使用python 3.2)

我需要能够:

  • 使用子进程运行命令
  • 该命令的两个 stdout/stderr 都需要实时打印到终端(无论它们是否都出现在 stdout 或 stderr 或其他上都没有关系
  • 同时,我需要一种方法来了解该命令是否向 stderr 打印了任何内容(最好是打印的内容)。

我玩过子进程管道以及在 bash 中进行奇怪的管道重定向,以及使用 tee,但到目前为止还没有找到任何可行的方法。这有可能吗?

【问题讨论】:

    标签: python subprocess pipe stdout stderr


    【解决方案1】:

    试试这样的:

    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/

    【讨论】:

      【解决方案2】:

      我的解决方案:

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

      【讨论】:

        猜你喜欢
        • 2017-11-24
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 2016-07-21
        • 1970-01-01
        • 2022-01-18
        • 2014-10-14
        • 2021-10-03
        相关资源
        最近更新 更多