Python子进程得到儿童的输出到文件和终端?

我正在运行一个脚本,通过使用执行一些可执行文件

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

outf / errf是None或文件描述符时( stdout / stderr不同文件)。

有没有什么办法可以执行每个exe文件,以便stdout和stderr将被写入文件和终端?

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", "ab"], close_fds=True, stdout=outf, stderr=errf) 

使用| 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中。