Pythonでは、sys.stdout
とwith open
を組み合わせることで、出力先を柔軟に切り替えることが可能です。具体的なコードは以下の通りです。
import sys
import contextlib
@contextlib.contextmanager
def smart_open(filename=None):
if filename and filename != '-':
fh = open(filename, 'w')
else:
fh = sys.stdout
try:
yield fh
finally:
if fh is not sys.stdout:
fh.close()
# ファイルへの書き込み
with smart_open('some_file') as fh:
print('some output', file=fh)
# 標準出力への書き込み
with smart_open() as fh:
print('some output', file=fh)
# 標準出力への書き込み('-'を指定)
with smart_open('-') as fh:
print('some output', file=fh)
このコードでは、smart_open
という関数を定義しています。この関数は、ファイル名を引数として受け取り、そのファイル名が指定されていないか、’-‘が指定されている場合は標準出力(sys.stdout
)を、それ以外の場合は指定されたファイルを開きます。そして、with
ブロックが終了すると、標準出力でない場合に限り、ファイルを閉じます。
このように、Pythonのwith open
とsys.stdout
を組み合わせることで、出力先を柔軟に切り替えることができます。これは、ログ出力やデバッグ情報の出力など、出力先が動的に変わる可能性がある場合に非常に便利です。