neu*_*ino 4 python stdout file
我有一个脚本接受一个文件名作为参数而不是打开它并写一些东西.
我使用with声明:
with open(file_name, 'w') as out_file:
...
out_file.write(...)
Run Code Online (Sandbox Code Playgroud)
sys.stdout如果没有file_name提供,我现在想写什么?
我是否一定需要在函数中包装所有操作并在之前设置条件?
if file_name is None:
do_everything(sys.stdout)
else:
with open(file_name, 'w') as out_file:
do_everything(out_file)
Run Code Online (Sandbox Code Playgroud)
from contextlib import contextmanager
@contextmanager
def file_or_stdout(file_name):
if file_name is None:
yield sys.stdout
else:
with open(file_name, 'w') as out_file:
yield out_file
Run Code Online (Sandbox Code Playgroud)
那你可以做
with file_or_stdout(file_name) as wfile:
do_stuff_writing_to(wfile)
Run Code Online (Sandbox Code Playgroud)