-
-
Save cliffxuan/2647913 to your computer and use it in GitHub Desktop.
A python IO class that writes to a coroutine.
This file contains 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 io | |
class CoroutineIO(io.TextIOBase): | |
""" | |
Creates an writable IO interface to a coroutine. | |
""" | |
def __init__(self, coroutine): | |
""" | |
Creates a new IO object with a coroutine. The | |
coroutine should take no arguments. | |
""" | |
self.coroutine = coroutine() | |
self.coroutine.next() # prime the pump | |
def read(self): | |
""" | |
This method isn't implemented since this is writable IO. | |
""" | |
raise IOError('CoroutineIO is writeonly.') | |
def write(self, x): | |
""" | |
Write something to the coroutine. | |
""" | |
self.coroutine.send(x) | |
def line_num_print(): | |
cnt = 0 | |
while True: | |
cnt += 1 | |
item = (yield) | |
print "%d: %s" % (cnt, item) | |
c = CoroutineIO(line_num_print) | |
c.write("Help!") | |
c.write("I'm trapped in python!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment