Created
December 2, 2014 21:18
-
-
Save cfobel/b60cfc793247cdbdc1c7 to your computer and use it in GitHub Desktop.
Example using greenlets to provide a blocking interface to asynchronously accept values from a GUI.
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
''' | |
Example using greenlets to provide a blocking interface to asynchronously | |
accept values from a GUI. | |
''' | |
import gtk | |
from pygtkhelpers.delegates import WindowView | |
from greenlet import greenlet | |
class View(WindowView): | |
def __init__(self): | |
self.entry_callback_greenlet = None | |
super(View, self).__init__() | |
def create_ui(self): | |
self.widget = gtk.Window() | |
box = gtk.VBox() | |
self.button = gtk.Button() | |
self.button.set_label('Push me') | |
self.text_input = gtk.Entry() | |
box.pack_start(self.text_input) | |
box.pack_start(self.button) | |
self.widget.add(box) | |
self.entry_callback_greenlet = greenlet(self.process_commands) | |
self.entry_callback_greenlet.switch() | |
def on_widget__delete_event(self, window, event): | |
self.hide_and_quit() | |
def on_button__clicked(self, *args): | |
if self.entry_callback_greenlet is not None: | |
# Return current text input contents to `read_next_char` parent. | |
self.entry_callback_greenlet.switch(self.text_input.get_text()) | |
def read_next_char(self): | |
g_self = greenlet.getcurrent() | |
self.text_input.set_text('') | |
# Jump to the parent (GTK thread), waiting for the next input value. | |
# __NB__ This is a blocking call. | |
next_char = g_self.parent.switch() | |
return next_char | |
def process_commands(self): | |
while True: | |
print 'GOT: ', self.read_next_char() | |
if __name__ == '__main__': | |
view = View() | |
view.show_and_run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment