2011-02-13 73 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中。