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
How about opening a new fd for sys.stdout? This way you won't have any problems closing it:
if not target: target = "/dev/stdout" with open(target, 'w') as f: f.write(content)