Skip to content

Instantly share code, notes, and snippets.

@markwatson
Created April 26, 2012 19:07
Show Gist options
  • Save markwatson/2502054 to your computer and use it in GitHub Desktop.
Save markwatson/2502054 to your computer and use it in GitHub Desktop.
A python IO class that writes to a coroutine.
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