vendredi 25 avril 2014

Context manager for optionally redirected I/O


Vote count:

0




I'm often faced with the situation that depending on some command line argument, input might either come from a file or standard input. The same goes for output. I really like how context managers in python 3 work, and therefore try to make all my open calls part of some with statement. But in this case, I'm having trouble.



if args.infile:
with open(args.infile, "r") as f:
process(f)
else:
process(sys.stdin)


is already clumsy, and with both input and output I'd have to cater for four combinations. I would like something easier, e.g.



with (open(args.infile, "r") if args.infile
else DummyManager(sys.stdin)) as f:
process(f)


Is there something like this DummyManager in the python standard libraries? Something which implements the context manager protocol, but only to return a fixed value from its __enter__ method? I guess the most likely location for such a class would be contextlib, and since I didn't find anything like this there, perhaps there is no such thing. Are there other elegant solutions you can suggest?



asked 2 mins ago

MvG

20.9k

1 Answer



Vote count:

0




It's trivial to create one with contextlib.contextmanager:



from contextlib import contextmanager

@contextmanager
def dummy_manager(ob):
yield ob


That's it; this creates a context manager that does nothing but hand you ob back, and the __exit__ handler does exactly nothing.



answered 40 secs ago





Aucun commentaire:

Enregistrer un commentaire