Skip to content

Instantly share code, notes, and snippets.

@AnIrishDuck
Created March 12, 2013 22:12
Show Gist options
  • Save AnIrishDuck/5147566 to your computer and use it in GitHub Desktop.
Save AnIrishDuck/5147566 to your computer and use it in GitHub Desktop.
Pipe context manager.
import os
from contextlib import contextmanager
@contextmanager
def pipe(my_end):
"""
Context manager that produces a unidirectional pipe, automatically always
closing the other end of that pipe. Useful for creating pipes to use with
subprocesses.
If ``my_end`` is ``"r"``, then the write end of the pipe is always closed.
The read end is always closed if ``my_end`` is ``"w"``.
Yields ``(read_fd, write_fd)`` to the context.
"""
r, w = os.pipe()
try:
yield r, w
finally:
os.close(r if my_end == "r" else w)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment