Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet:
if target:
with open(target, 'w') as h:
h.write(content)
else:
sys.stdout.write(content)
I would like to rewrite it and handle both targets uniformly.
In ideal case it would be:
with open(target, 'w') as h:
h.write(content)
but this will not work well because sys.stdout is be closed when leaving with
block and I don't want that. I neither want to
stdout = open(target, 'w')
...
because I would need to remember to restore original stdout.
Related:
Edit
I know that I can wrap target
, define separate function or use context manager. I look for a simple, elegant, idiomatic solution fitting that wouldn't require more than 5 lines
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…