如何在 Python 中将子进程的结果同时输出到文件和终端
使用 subprocess.call() 时,可以指定文件描述符作为 outf 和 errf 将 stdout 和 stderr 重定向到特定文件。但是,这些结果不会同时显示在终端中。
使用 Popen 和线程的解决方案:
为了克服这个问题,我们可以直接利用 Popen 并利用stdout=PIPE 从子进程的 stdout 读取的参数。方法如下:
<code class="python">import subprocess from threading import Thread def tee(infile, *files): # Forward output from `infile` to `files` in a separate thread def fanout(infile, *files): for line in iter(infile.readline, ""): for f in files: f.write(line) t = Thread(target=fanout, args=(infile,) + files) t.daemon = True t.start() return t def teed_call(cmd_args, **kwargs): # Override `stdout` and `stderr` arguments with PIPE to capture standard outputs stdout, stderr = [kwargs.pop(s, None) for s in ["stdout", "stderr"]] p = subprocess.Popen( cmd_args, stdout=subprocess.PIPE if stdout is not None else None, stderr=subprocess.PIPE if stderr is not None else None, **kwargs ) # Create threads to simultaneously write to files and terminal 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)) # Join the threads to ensure IO completion before proceeding for t in threads: t.join() return p.wait()</code>
使用此函数,我们可以执行子进程并将其输出同时写入文件和终端:
<code class="python">outf, errf = open("out.txt", "wb"), open("err.txt", "wb") teed_call(["cat", __file__], stdout=None, stderr=errf) teed_call(["echo", "abc"], stdout=outf, stderr=errf, bufsize=0) teed_call(["gcc", "a b"], close_fds=True, stdout=outf, stderr=errf)</code>
以上是如何在 Python 中同时将子进程输出重定向到文件和终端?的详细内容。更多信息请关注PHP中文网其他相关文章!