Python スクリプトが外部で使用される方法を変更せずに、出力をファイルとターミナルにリダイレクトするには、次を使用できますpty.spawn(itself)
。
#!/usr/bin/env python
"""Redirect stdout to a file and a terminal inside a script."""
import os
import pty
import sys
def main():
print('put your code here')
if __name__=="__main__":
sentinel_option = '--dont-spawn'
if sentinel_option not in sys.argv:
# run itself copying output to the log file
with open('script.log', 'wb') as log_file:
def read(fd):
data = os.read(fd, 1024)
log_file.write(data)
return data
argv = [sys.executable] + sys.argv + [sentinel_option]
rc = pty.spawn(argv, read)
else:
sys.argv.remove(sentinel_option)
rc = main()
sys.exit(rc)
モジュールが (Windows で) 利用できない場合は、より移植性の高い関数pty
に置き換えることができますが、疑似端末の代わりに通常のパイプを提供します。一部のプログラムの動作が変わる可能性があります。teed_call()
ファイルのようなオブジェクトで置き換えるよりもpty.spawn
およびベースのソリューションの利点は、ファイル記述子レベルで出力をキャプチャできることです。たとえば、スクリプトが stdout/stderr で出力を生成できる他のプロセスを開始した場合などです。関連する質問に対する私の回答を参照してください: Redirect stdout to a file in Python?subprocess.Popen
sys.stdout