2012-10-14 17 views
2

(使用Python 3.2目前)捕獲,並在同一時間用python的子輸出標準錯誤

我需要能夠:使用子

  • 標準輸出的/標準錯誤

    • 運行一個命令該命令需要實時打印到終端(無論它們是在stdout還是stderr或其他任何地方出現都沒關係)。同時,我需要一種方法來知道命令是否將任何內容打印到stderr (並且最好是它打印的內容)

    我與子管發揮各地以及做怪管道重定向在bash,以及使用tee,但作爲然而沒有發現任何東西,將工作。這是可能的嗎?

  • 回答

    1

    我的解決辦法:

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

    嘗試這樣:

    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這樣的:

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

    但似乎是在python3沒有這種功能。如果你沒有找到解決這個問題的方式,嘗試直接使用subprocess.Popen,如下所述:http://www.saltycrane.com/blog/2009/10/how-capture-stdout-in-real-time-python/

    相關問題