2011-02-13 51 views
14

我跑,通過使用Python子進程獲取兒童輸出到文件和終端?

subprocess.call(cmdArgs,stdout=outf, stderr=errf) 

outf/errf是無或文件描述符(不同的文件stdout/stderr)執行一些可執行的腳本。

有沒有什麼辦法可以執行每個exe文件,這樣stdout和stderr就會一起寫入文件和終端?

+1

[asyncio version](http://stackoverflow.com/a/25960956/4279) – jfs 2014-10-28 17:13:13

回答

22

call()功能只是Popen(*args, **kwargs).wait()。你可以直接調用Popen和使用stdout=PIPE參數從p.stdout閱讀:

import sys 
from subprocess import Popen, PIPE 
from threading import Thread 

def tee(infile, *files): 
    """Print `infile` to `files` in a separate thread.""" 
    def fanout(infile, *files): 
     for line in iter(infile.readline, ''): 
      for f in files: 
       f.write(line) 
     infile.close() 
    t = Thread(target=fanout, args=(infile,)+files) 
    t.daemon = True 
    t.start() 
    return t 

def teed_call(cmd_args, **kwargs):  
    stdout, stderr = [kwargs.pop(s, None) for s in 'stdout', 'stderr'] 
    p = Popen(cmd_args, 
       stdout=PIPE if stdout is not None else None, 
       stderr=PIPE if stderr is not None else None, 
       **kwargs) 
    threads = [] 
    if stdout is not None: threads.append(tee(p.stdout, stdout, sys.stdout)) 
    if stderr is not None: threads.append(tee(p.stderr, stderr, sys.stderr)) 
    for t in threads: t.join() # wait for IO completion 
    return p.wait() 

outf, errf = open('out.txt', 'w'), open('err.txt', 'w') 
assert not teed_call(["cat", __file__], stdout=None, stderr=errf) 
assert not teed_call(["echo", "abc"], stdout=outf, stderr=errf, bufsize=0) 
assert teed_call(["gcc", "a b"], close_fds=True, stdout=outf, stderr=errf) 
+0

謝謝,你會怎麼做,而不是subprocess.Call我想運行多個執行使用subprocess.Popen(而不是Call),其中每個執行程序寫入不同的文件和終端 – user515766 2011-02-14 09:02:38

0

使用| tee將輸出重定向到一個名爲out.txt在獲取終端上的輸出文件。

import subprocess 

# Run command and redirect it by | tee to a file named out.txt 
p = subprocess.Popen([command, '|', 'tee', 'out.txt']) 
p.wait() 

在windows平臺上,沒有|開球。我們需要使用Powershell。因此,第三行的命令變爲:

# Run command in powershell and redirect it by | tee to a file named out.txt 
p = subprocess.Popen(['powershell','command, '|', 'tee', 'out.txt']) 

通過這種方式,打印stdout並將stdout存儲在文件out.txt中。