#!/usr/bin/python import time import random def generator(): position = 1 direction = 1 while True: received_value = yield position position += direction assert received_value in [ None, 'reverse' ] if received_value == 'reverse' or direction == 1 and position == 10 or direction == -1 and position == 1: direction *= -1 def main(): gen = generator() first_time = True while True: if random.random() < 0.9 or first_time: first_time= False value = gen.send(None) show_reverse = '' else: show_reverse = ' manual reverse' value = gen.send('reverse') time.sleep(0.1) print '%2d >%s*%s< %s' % (value, (value - 1) * ' ', (10 - value) * ' ', show_reverse) main()