如何在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中文網其他相關文章!