はじめに
subprocessで起動したプロセスのコンソール出力を取得・保存するコードサンプル。
以下のコードで、test.exeやtest.batのコンソール出力をテキストファイルに保存可能。
キーワード: subprocess.Popen、外部コマンド実行、標準出力リダイレクト
処理方法
-
subprocess.Popen(.., stdout=.., stderr=..)
を使用、 -
stderr=subprocess.PIPE
によりコンソール出力を当プロセスに流し、proc.communicate()
で、起動したプロセスの終了を待機。 - (
proc.communicate()
がないと、終了を待たずに続行、並列処理となる)
テストコード
(ポイントとなる箇所に、コメントで説明を付記)
trial.py
# -*- coding: utf-8 -*-
# subprocessで起動したプロセスのコンソール出力を取得・保存するには
# ref: https://www.it-swarm-ja.tech/ja/python/subprocesscall%EF%BC%88%EF%BC%89%E3%81%AE%E5%87%BA%E5%8A%9B%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B/968744582/
import subprocess
def main(): # 実行切替用
run__main1()
# sec: コンソール出力を取得・保存
def run__main1():
# 結果:
# test.exeのコンソール出力保存可
# test.batもコンソール出力保存可、.batも可
# case: FAIL
# subprocess.call("test.exe > res.log.txt")
# case: Popen(.., stdout=..)を使用
with open("res.log.txt", 'w') as file_log:
proc = subprocess.Popen(
["test.bat"],
stdout=file_log, stderr=subprocess.PIPE) # 出力が必要な場合はstdout・stderr引数を利用
proc.communicate() # これで待機
print("return code:", proc.returncode) # DEBUG: 待機・終了確認用
# case: end
print("ended.")
# sec: entry
if __name__ == "__main__": main()
参考