Skip to content
Advertisement

How to handle both `with open(…)` and `sys.stdout` nicely?

Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet:

JavaScript

I would like to rewrite it and handle both targets uniformly.

In ideal case it would be:

JavaScript

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

JavaScript

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

Advertisement

Answer

Just thinking outside of the box here, how about a custom open() method?

JavaScript

Use it like this:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement