Created
March 12, 2013 22:12
-
-
Save AnIrishDuck/5147566 to your computer and use it in GitHub Desktop.
Pipe context manager.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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